logical indexing from matrix to vector
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
Voss
2021년 12월 21일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!