logical indexing from matrix to vector
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 21 Dec 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 Comments
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!