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!