我是Matlab的新手,我无法有效地解决以下问题。
我有两个数组(两个都是2D),我想通过col检查array1 col,知道在array2的每个col中出现了多少个元素(比较col到col)
例如
array1
---------
'a1' 'b1' 'c1'
'd1' 'e1' 'f1'
array2
----------
'a1' 'a1' 'b1' 'b1' 'a1'
'd1' 'd1' 'c1' 'd1' 'c1'
'c1' 'c1' 'b1' 'd1' 'd1'
我想获得以下输出
2 elements from array1 col1 appear in array2 col1
2 elements from array1 col1 appear in array2 col2
0 elements from array1 col1 appear in array2 col3
1 elements from array1 col1 appear in array2 col4
2 elements from array1 col1 appear in array2 col5
0 elements from array1 col2 appear in array2 col1
0 elements from array1 col2 appear in array2 col2
1 elements from array1 col2 appear in array2 col3
1 elements from array1 col2 appear in array2 col4
0 elements from array1 col2 appear in array2 col5
1 elements from array1 col3 appear in array2 col1
1 elements from array1 col3 appear in array2 col2
1 elements from array1 col3 appear in array2 col3
0 elements from array1 col3 appear in array2 col4
1 elements from array1 col3 appear in array2 col5
and so on
现在我尝试使用以下丑陋的代码获取部分输出
for i=1:size(Array1,2)
for m=1:size(Array1,1)
element = Array1(i,m);
indx =find(ismember(Array2,element));
Array_match(indx) = Array_match(indx) + 1;
end
for s=2:size(Array1,1)
if length(char(Array1(s,i))) > 0
tt= tt + 1;
end
length(Array_test_words(s,i))
end
Indx2 = find((Array_match) > tt);
end
答案 0 :(得分:3)
假设输入单元格数组包含单个字符串的所有单元格,这可能对您有用 -
%// Input cell arrays
array1 = {
'a1' 'b1' 'c1'
'd1' 'e1' 'f1'}
array2 = {
'a1' 'a1' 'b1' 'b1' 'a1'
'd1' 'd1' 'c1' 'd1' 'c1'
'c1' 'c1' 'b1' 'd1' 'd1'}
%// Convert input cell arrays to numeric arrays
array1n = char(array1)-0
array1n = reshape(array1n(:,1) * 1000 + array1n(:,2),size(array1))
array2n = char(array2)-0
array2n = reshape(array2n(:,1) * 1000 + array2n(:,2),size(array2))
out = squeeze(sum(any(bsxfun(@eq,array2n,permute(array1n,[3 4 1 2])),1),3))
输出 -
out =
2 0 1
2 0 1
0 1 1
1 1 0
2 0 1
答案 1 :(得分:2)
将unique
应用于两个数组的串联,以将单元格转换为数字标签。删除第二个数组的每列中的重复值。然后使用bsxfun
测试相等性,并汇总每个列组合的结果:
[~, ~, labels] = unique({array1{:} array2{:}});
a1 = reshape(labels(1:numel(array1)),size(array1)); %// array1 as numeric labels
a2 = reshape(labels(numel(array1)+1:end), size(array2)); %// same for array2
a2 = sort(a2);
a2(diff([NaN(1,size(a2,2)); a2])==0) = NaN; %// remove repeated values
m = bsxfun(@eq, permute(a1, [1 3 2]), permute(a2, [3 1 4 2])); %// find matches
result = squeeze(sum(reshape(m, [],size(a1,2),size(a2,2)), 1));
在你的例子中,这给出了
result =
2 2 0 1 2
0 0 1 1 0
1 1 1 0 1