How to construct a binary matrix reporting 1 in case of equal rows of two arrays of different dimensions?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MRC
el 6 de Ag. de 2014
Editada: Ashish Gudla
el 6 de Ag. de 2014
Hi, I have a matrix nxk
A=[ 1 2; 3 4; 5 6; 7 8]
and a matrix B mxk (m can be > = or < n)
B=[ 2 3; 4 5; 1 2; 5 6; 10 23; 7 8]
Each row of B is different.
I want to construct a matrix C nxm in which the hi-th element is 1 if A(h,:)=B(i,:), i.e.
C=[0 0 1 0 0 0; 0 0 0 0 0 0; 0 0 0 1 0 0; 0 0 0 0 0 1];
without looping.
2 comentarios
Image Analyst
el 6 de Ag. de 2014
Why the fear of looping for such a nano-sized matrix? Too much caffeine?
Respuesta aceptada
Ashish Gudla
el 6 de Ag. de 2014
Editada: Ashish Gudla
el 6 de Ag. de 2014
You could create the 'C' matrix with all zeros and then, find the positions where its supposed to be '1' and replace it.
To find the positions where there would be '1', you can use "ismember" function with rows( see doc ) to get the lowest index of each row in A that appears in B.
[a1,~] = size(A);
[b1,~] = size(B);
[~,t2]=ismember(A,B,'rows');
t1 = 1:a1;
t1= t1(t2~=0); %ignore zero indices
t2 = t2(t2~=0);
C = zeros(a1,b1);
i = sub2ind(size(C),t1,t2');
C(i) =1;
0 comentarios
Más respuestas (1)
Chris Turnes
el 6 de Ag. de 2014
Editada: Chris Turnes
el 6 de Ag. de 2014
One way to do this without looping would be to exploit the property that two vectors w and v are equal if and only if
Using this, you could construct each term and compare:
>> IP = A*B.';
>> An = sum(abs(A).^2, 2); % abs only necessary if data is complex
>> Bn = sum(abs(B).^2, 2);
>> C = (IP == An*ones(1, length(Bn))) & (IP == ones(length(An), 1)*Bn.');
This is a way of vectorizing the operation, but it will use much more memory than looping would.
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!