How to Insert desired rows from one matrix into a new one

This is a small example of the overall problem:
What I want to do is essentially filter out rows from the matrix with some desired property (in this case, that the sum of the row = 2), and then save it to a new matrix.
Any ideas? Thanks!
v = [0 2 4 6 2;
2 0 0 0 0];
count = 0;
for i = 1:2
k = v(i,:)
if sum(k) == 2
count = count + 1;
P(count, :) = k;
end
end

回答 (2 件)

Walter Roberson
Walter Roberson 2012 年 10 月 4 日

1 投票

P = v(sum(v,2) == 2, :);
Breaking this into steps:
t = sum(v,2); %sum each row of the matrix. "2" means rows
rowmatches = (t == 2); %true where the sum was 2
P = v(rowmatches, :); %logical indexing to do the extraction
Matt Fig
Matt Fig 2012 年 10 月 4 日
編集済み: Matt Fig 2012 年 10 月 4 日

0 投票

v = [2 0 0;1 0 1;4 5 6;-1 1 2; 2 3 4] % Sample array.
P = v(sum(v,2)==2,:)

この質問は閉じられています。

質問済み:

Max
2012 年 10 月 4 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by