How to compare two matrices of different dimensions?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
MRC
am 29 Apr. 2014
Beantwortet: Georgia Petsios
am 18 Jan. 2018
I have a matrix B of dimension bx2 and a matrix A of dimension ax5 with the following characteristics:
B=[1 18; 1 19; 3 1; 4 18; 4 20; 5 18; 6 12] %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 1 1 0 0; 2 0 0 0 0; 3 1 0 0 0; 4 1 0 0 1; 5 1 0 0 0; 6 0 1 0 0]
Basically 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).
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 29 Apr. 2014
Bearbeitet: Andrei Bobrov
am 30 Apr. 2014
B=[1 18; 1 19; 3 1; 4 18; 4 20; 5 18; 6 12];
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];
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))];
add
A = [5 18 19 19 20
2 7 8 9 10
6 11 12 13 14
1 18 19 19 20
4 18 19 19 20
8 30 21 0 15];
B=[1 18; 1 19; 3 1; 4 18; 4 20; 5 18; 6 12];
x = accumarray(B(:,1),B(:,2),[max(B(:,1)),1],@(x){x});
C = zeros(size(A));
C(:,1) = A(:,1);
[l,ii] = ismember(A(:,1),(1:numel(x))');
ix = find(l);
ia = ii(l);
C(l,2:end) = cell2mat(arrayfun(@(y,z)ismember(A(y,2:end),x{z}),ix,ia,'un',0));
2 Kommentare
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!