How to Insert desired rows from one matrix into a new one
Info
This question is closed. Reopen it to edit or answer.
Show older comments
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
Answers (2)
Walter Roberson
on 4 Oct 2012
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
v = [2 0 0;1 0 1;4 5 6;-1 1 2; 2 3 4] % Sample array.
P = v(sum(v,2)==2,:)
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!