Compare two matrices of different dimensions

1 回表示 (過去 30 日間)
MRC
MRC 2014 年 4 月 29 日
コメント済み: MRC 2014 年 4 月 29 日
I have a matrix B of dimension bx2 and a matrix A of dimension ax5 with the following characteristics:
B=[3 1;
3 2;
3 3;
5 18] %In the first column of B elements are always in ascending order but can be repeated more than once
A=[1 18 19 19 20;
2 7 8 9 10;
3 1 2 2 3;
4 18 19 19 20;
5 18 19 19 20;
6 11 12 13 14] %In the first column of A elements are always in ascending order, they start from 1 and end at a=6 and they are at a distance of 1
I want to construct a matrix C of dimension ax5
C=[1 0 0 0 0;
2 0 0 0 0;
3 1 1 1 1;
4 0 0 0 0;
5 1 0 0 0;
6 0 0 0 0]
In C I do the following: I take A(i,1) and pick the rows j of A with B(j,1) equal to A(i,1); for these rows I pick B(j,2) and reports C(i,h)=1 is B(j,2)=A(i,h).
If B(:,1) started with 1 and ended with 6 a possible answer would be
x = accumarray(B(:,1),B(:,2),[max(B(:,1)),1],@(x){x});
C = [A(:,1),cell2mat(arrayfun(@(z)ismember(A(z,2:end),x{z}),A(:,1),'un',0))]
as suggested here
But in this case B(:,1) does not necessarily start with 1 and end with 6 even if it has for sure elements <=6 and >=1
  3 件のコメント
the cyclist
the cyclist 2014 年 4 月 29 日
Should the third row of C actually be
[3 1 1 1 1]
?
MRC
MRC 2014 年 4 月 29 日
Yes, thanks question edited.

サインインしてコメントする。

回答 (1 件)

the cyclist
the cyclist 2014 年 4 月 29 日
B=[3 1;
3 2;
3 3;
5 18] %In the first column of B elements are always in ascending order but can be repeated more than once
A=[1 18 19 19 20;
2 7 8 9 10;
3 1 2 2 3;
4 18 19 19 20;
5 18 19 19 20;
6 11 12 13 14] %In the first column of A elements are always in ascending order, they start from 1 and end at a=6 and they are at a distance of 1
C = zeros(size(A));
C(:,1) = A(:,1);
for ii = 1:size(A,1)
C(ii,2:end) = ismember(A(ii,2:end),B(B(:,1)==ii,2:end))
end
  1 件のコメント
MRC
MRC 2014 年 4 月 29 日
Any idea without looping?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by