logical indexing from matrix to vector
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
How to extract nonzero columns from rows (in a matrix whose each rows have only one column as 1 and others 0) and put them into a vector rows?
A=rand(4,5);
B=rand(4,5);
C=rand(4,5);
D=logical([1 0 0 0 0; 0 0 0 0 1; 0 1 0 0 0; 0 0 1 0 0]);% each row has 1 nonzero column
E=zeros(4,3);
%get first column of E, E(:,1) to be all rows of A at the nonzero column of A. For instance,
% F=zeros(4,5), then F(D)=A(D) will put those nonzero columns of A into matching positions in F. But I want those to go to E(:,1).
% Then, E(:,2) contains all elements B(D), and E(:,3) contains all elements
% C(D).
0 Kommentare
Akzeptierte Antwort
Voss
am 21 Dez. 2021
Here is one way:
A=rand(4,5);
B=rand(4,5);
C=rand(4,5);
display(A);
display(B);
display(C);
D=logical([1 0 0 0 0; 0 0 0 0 1; 0 1 0 0 0; 0 0 1 0 0]);% each row has 1 nonzero column
display(D);
E=zeros(4,3);
[r,c] = find(D);
for i = 1:numel(r)
E(r(i),:) = [A(r(i),c(i)) B(r(i),c(i)) C(r(i),c(i))];
end
display(E);
0 Kommentare
Weitere Antworten (0)
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!