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
댓글 수: 0
답변 (2개)
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
댓글 수: 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,:)
댓글 수: 0
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!