matlab - Compare and find strings in 2 dimensional array -
i new matlab , stuck in efficiently solving following problem.
i have 2 arrays (both of them 2d) , want check array1 col col know how many elements appear in each col of array2 (compare col col)
for example
array1 --------- 'a1' 'b1' 'c1' 'd1' 'e1' 'f1' array2 ---------- 'a1' 'a1' 'b1' 'b1' 'a1' 'd1' 'd1' 'c1' 'd1' 'c1' 'c1' 'c1' 'b1' 'd1' 'd1'
i trying following output
2 elements array1 col1 appear in array2 col1 2 elements array1 col1 appear in array2 col2 0 elements array1 col1 appear in array2 col3 1 elements array1 col1 appear in array2 col4 2 elements array1 col1 appear in array2 col5 0 elements array1 col2 appear in array2 col1 0 elements array1 col2 appear in array2 col2 1 elements array1 col2 appear in array2 col3 1 elements array1 col2 appear in array2 col4 0 elements array1 col2 appear in array2 col5 1 elements array1 col3 appear in array2 col1 1 elements array1 col3 appear in array2 col2 1 elements array1 col3 appear in array2 col3 0 elements array1 col3 appear in array2 col4 1 elements array1 col3 appear in array2 col5 , on
now tried below ugly code getting partial output
for i=1:size(array1,2) m=1:size(array1,1) element = array1(i,m); indx =find(ismember(array2,element)); array_match(indx) = array_match(indx) + 1; end 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
apply unique
concatenation of both arrays transform cells numeric labels. remove repeated values in each column of second array. test equality bsxfun
, aggregate results each combination of columns:
[~, ~, labels] = unique({array1{:} array2{:}}); a1 = reshape(labels(1:numel(array1)),size(array1)); %// array1 numeric labels a2 = reshape(labels(numel(array1)+1:end), size(array2)); %// same 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));
in rexample gives
result = 2 2 0 1 2 0 0 1 1 0 1 1 1 0 1
Comments
Post a Comment