Correspondance matrix for matching values in two vectors

1 次查看(过去 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?

采纳的回答

Bruno Luong
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
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
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
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by