Eliminating Multiple rows using 'if' conditional
2 次查看(过去 30 天)
显示 更早的评论
Is it possible to eliminate multipe rows of a matrix using IF conditional?
A=[1 1875 507
1 1880 508 %repeat
1 1885 508 %repeat (eliminate this row)
1 1890 508 %repeat
1 1895 512
2 1720 501
2 1730 502 %repeat
2 1740 502 %repeat (eliminate this row)
2 1750 502 %repeat (eliminate this row)
2 1760 502 %repeat
2 1770 505]
Here, A(3,:), A(8:9,:) are to be eliminated.
So that the the result would look like:
B=[1 1875 507
1 1880 508
1 1890 508
1 1895 512
2 1720 501
2 1730 502
2 1760 502
2 1770 505]
How can such elimination be done using IF loop for a matrix bigger than this where it is very inefficient to do so for every unique value in Column1?
Thank you
0 个评论
采纳的回答
the cyclist
2012-7-20
Given your very special requirement for first and last rows, you might be able to use the unique() command. Does this work for you?
[~,indexToFirst] = unique(A(:,[1 3]),'rows','first');
[~,indexToLast] = unique(A(:,[1 3]),'rows','last');
indexToFirstAndLastRows = union(indexToFirst,indexToLast);
A = A(indexToFirstAndLastRows,:)
更多回答(1 个)
Walter Roberson
2012-7-19
Yes, it is possible to eliminate multiple rows using "if" conditions. For example,
if 1 + 1 == 2
A([3 8:9], :) = [];
end
Often it is cleaner and more efficient to use logical indexing rather than "if" conditions.
The pattern you are looking for seems to be "within each unique value for the first column, if there are more than two consecutive rows with the same value for the third column, then eliminate all except the first and the last of them." Is that what you are looking for?
If so then what should happen if we add an additional entry to the end of the matrix,
2 1725 502
then should there be an implicit re-sorting to move the 1725 to between the 1720 and 1730, thus triggering the 1730 entry to be eliminated? Or since the 1725 entry would be "after" the other entries, should the 1740, 1750, 1760 and 1770 entries all be removed, even though the 1770 is a different column 3, under the rule that "all" entries between the first and last with the same third value should be eliminated?
2 个评论
Walter Roberson
2012-7-19
min() and max() is a different and easier calculation than removing values positionally. If you want min() and max() you can do your calculation using accumarray()
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!