logical indexing from matrix to vector

4 ビュー (過去 30 日間)
MatG
MatG 2021 年 12 月 21 日
回答済み: Voss 2021 年 12 月 21 日
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).

採用された回答

Voss
Voss 2021 年 12 月 21 日
Here is one way:
A=rand(4,5);
B=rand(4,5);
C=rand(4,5);
display(A);
A = 4×5
0.4104 0.9407 0.5917 0.6464 0.7284 0.6918 0.8538 0.6330 0.5557 0.5605 0.1275 0.8258 0.1423 0.8855 0.3392 0.2219 0.1713 0.1226 0.2026 0.0638
display(B);
B = 4×5
0.1526 0.9030 0.3792 0.0172 0.4932 0.0312 0.8822 0.1125 0.2305 0.6067 0.3733 0.2005 0.6237 0.5705 0.0556 0.3156 0.5108 0.7459 0.5075 0.5017
display(C);
C = 4×5
0.4056 0.3240 0.5035 0.9342 0.7651 0.3437 0.9692 0.8953 0.2602 0.0158 0.9978 0.0599 0.1278 0.8558 0.4685 0.9000 0.4657 0.6759 0.1337 0.0315
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);
D = 4×5 logical array
1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0
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);
E = 4×3
0.4104 0.1526 0.4056 0.5605 0.6067 0.0158 0.8258 0.2005 0.0599 0.1226 0.7459 0.6759

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by