我有一个名为struct
的结构1x300,包含3个字段,但我只使用名为way
的第三个字段。对于每300行,该字段是索引的垂直。
这里有一个3行的例子来解释我的问题:我想搜索第一行的最后一个索引是否出现在字段way
的另一个向量(行)中。
way
[491751 491750 491749 492772 493795 494819 495843 496867]
[491753 491754 491755 491756]
[492776 493800 494823 495847 496867]
我尝试过交叉功能:
Inter=intersect(struct(1).way(end), struct.way);
但是Matlab给我一个错误:
Error using intersect (line 80)
Too many input arguments.
Error in file2 (line 9)
Inter=intersect(struct(1).way(end), struct.way);
我不明白为什么会出现这个错误。任何解释和/或其他解决方案?
答案 0 :(得分:2)
将数据定义为
st(1).way = [491751 491750 491749 492772 493795 494819 495843 496867];
st(2).way = [491753 491754 491755 491756];
st(3).way = [492776 493800 494823 495847 496867]; % define the data
sought = st(1).way(end);
如果您想知道哪些向量包含所需的值:将所有向量打包到一个单元格数组中,并使用匿名函数将其传递给cellfun
,如下所示:
ind = cellfun(@(x) ismember(sought, x), {st.way});
这给出了:
ind =
1×3 logical array
1 0 1
如果你想知道匹配的每个向量索引:修改匿名函数以输出带索引的单元格:
ind = cellfun(@(x) {find(x==sought)}, {st.way});
或等效
ind = cellfun(@(x) find(x==sought), {st.way}, 'UniformOutput', false);
结果是:
ind =
1×3 cell array
[8] [1×0 double] [5]
或者,要排除参考向量:
n = 1; % index of vector whose final element is sought
ind = cellfun(@(x) {find(x==st(n).way(end))}, {st([1:n-1 n+1:end]).way});
答案 1 :(得分:0)
你可能想要使用ismember
。
考虑您传递给intersect
/ ismember
函数的内容,struct.way
不是有效参数,您可能需要循环迭代结构的每一行(在这种情况下,使用单元格数组或具有相等长度行的矩阵会更容易。)
output = zeros(300);
for ii = 1:300
for jj = 1:300
if ii ~= jj && ismember(struct(ii).way(end), struct(jj).way)
output(ii,jj) = 1;
end
end
end
现在你有一个矩阵output
,其中1的元素标识结构行ii
中的最后一个元素与向量struct(jj).way
之间的匹配,其中{{1是矩阵行号,列号是ii
。