Correspondance matrix for matching values in two vectors
4 ビュー (過去 30 日間)
古いコメントを表示
Assume two vectors with 20 values as follows:
a=[2 2 2 2 2 1 1 1 3 3 2 2 1 1 1 1 3 3 2 2];
b=[1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 ];
Now I try to count how the values in vector a match to those in vector b. From visual relation I can make these three observations: - value 2 in vector a corresponds 6 times to value 1 in vector b, 3 times to value 2 in vector b and there is no matching 3 value in vector b; - value 1 in vector a has 0 corresponding value 1 in vector b, corresponds 7 times to value 2 in vector b and there is no matching 3 value in vector b; - value 3 in vector a corresponds 1 time to value 1 in vector b, 3 times to value 2 in vector b and there is no matching 3 value in vector b;
I would like to display these three observations in a matrix where each row corresponds to one observation:
c=[6 3 0; 0 7 0; 1 3 0];
I can envisage that the code for this possibly first requires the sorting of the data so that numbers in vector a have ascending order, which would mean that the resulting matrix becomes:
c=[0 7 0; 6 3 0; 1 3 0];
Can anybody tell me how to code the solution?
0 件のコメント
採用された回答
Bruno Luong
2018 年 10 月 16 日
編集済み: Bruno Luong
2018 年 10 月 16 日
That gives the second form of your expected result, but assuming elements are 1,2,..., n
n = 3;
c = accumarray([a(:),b(:)],1,[n n])
If the values do not meet the above requirement, the this will do:
u = union(a,b); % or u = unique(a)?
[~,ia] = ismember(a(:),u);
[bb,ib] = ismember(b(:),u);
n = length(u);
c = accumarray([ia(bb),ib(bb)],1,[n n])
8 件のコメント
Bruno Luong
2018 年 10 月 16 日
編集済み: Bruno Luong
2018 年 10 月 16 日
No, in my case two ISMEMBER checks on the same set U, which can be derived from UNIQUE(A) or UNION(A,B) (I have a doubt which one OP wants), so it's not independent in this sense.
If you still don't see the difference, never-mind, and believe Andrei see it.
Stephen23
2018 年 10 月 16 日
編集済み: Stephen23
2018 年 10 月 16 日
"is this behavious you expect from 2 (independent) UNIQUE ?"
As long as the vectors both contain the same values, then it will work (and be reasonably efficient). This is an assumption, just like your assumption of your original answer that the values are 1,2,...N, but I missed that 3, so it turns out to be invalid for this data.
その他の回答 (1 件)
Andrei Bobrov
2018 年 10 月 16 日
a = [2 2 2 2 2 1 1 1 3 3 2 2 1 1 1 1 3 3 2 2];
b = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1];
[a1,~,c] = unique(a);
n = numel(a1);
out = zeros(n);
a2 = [a1,a1(end)+1];
for ii = 1:n
out(ii,:) = histcounts(b(c == ii),a2);
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!