我在 Matlab 中有以下包含各种字母组合的单元格 a,b,c,d
%all combinations containing 'a' and/or 'b'
G1={'a', 'ab', 'ac', 'ad', 'abc', 'acd', 'abd', 'abcd', 'b', 'bc', 'bd', 'bcd'};
%all combinations containing 'c' and/or 'd'
G2={'c', 'ac', 'bc', 'cd', 'abc', 'acd', 'bcd', 'abcd', 'd', 'ad', 'bd', 'abd'};
%all combinations containing 'c'
G3={'c', 'ac', 'bc', 'cd', 'acd', 'abd', 'bcd', 'abcd'};
然后我构建了一个all
维度的单元格
allsize=size(G1,2)*size(G2,2)*size(G3,2);
包含将 的一个元素G1
与 的一个元素G2
与 的一个元素匹配的所有可能方式G3
。
all=cell(allsize,3);
count=0;
for h=1:size(G1,2)
for k=1:size(G2,2);
for j=1:size(G3,2);
count=count+1;
all(count,1)=G1(h);
all(count,2)=G2(k);
all(count,3)=G3(j);
end
end
end
问题:我想构造一个check
维度向量allsize x 1
,check(l)=1
如果[all(l,1)
包含a
并 all(l,2)
包含c
]或[all(l,1)
包含b
并 all(l,2)
包含d
],否则为零。
我在编写if 条件时遇到问题
check=zeros(allsize,1);
for l=1:allsize
%if [all(l,1) contains a and all(l,2) contains c] or [all(l,1) contains b and all(l,2) contains d]
check(l)=1;
%end
end
你能提供一些帮助吗?
(对于 if 语句,总是最好显示您尝试过的内容而不是一些伪代码,但是...)
首先all
用作变量名是不好的——它是一个重要的内置函数,你可能想要使用它......我在allG
下面重命名了它。但你可能想要这样的东西:
check(l) = (any(allG{l,1}=='a') && any(allG{l,2}=='c')) || ...
(any(allG{l,1}=='b') && any(allG{l,2}=='d'))
注意我没有使用if
语句,因为右手边的计算结果是一个逻辑值(一个真/假值),它通常可以像 1 和 0 一样使用......
同样在上面,我们将字符串视为字符数组,因此类似于'abcd'=='b'
返回一个[0 1 0 0]
逻辑数组……然后我们使用它any()
来查看是否有任何值是 1(真)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句