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일
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일
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