Remove array elements but also store the element indices that were not removed
古いコメントを表示
I have a long array e.g. a = ["a", "b", "c", "d", "e" ,"f"]
I want to remove first and 5th element. u = [1,5]
For that I can do a(u) = []
But I also want the element indices that were not removed i.e. I want output as [2 3 4 6]
I tried a(~u) but it is not working.
採用された回答
その他の回答 (1 件)
There are several ways. Here are two:
a = ["a", "b", "c", "d", "e" ,"f"]
rowsToRemove = [1, 5];
aExtracted = a(rowsToRemove)
aKept = setdiff(a, aExtracted)
% Another way
aKept2 = a; % Initialize
aKept2(rowsToRemove) = []
3 件のコメント
Image Analyst
2022 年 11 月 23 日
編集済み: Image Analyst
2022 年 11 月 23 日
I know you really really wanted to use ~ but I think using [] is easier and preferable. This is about as compact as you can get (two lines of code to give the two vectors) and doesn't use setdiff, though it removes the elements from a, thus changing it. If you want to keep a copy of the original, then make a copy first.
a = ["a", "b", "c", "d", "e" ,"f"];
rowsToRemove = [1, 5];
aExtracted = a(rowsToRemove)
a(rowsToRemove) = []
If you really insist on using ~, here is one way is can be done:
a = ["a", "b", "c", "d", "e" ,"f"]'
indexes = 1 : numel(a);
rowsToRemove = [1, 5];
logicalIndexes = ismember(indexes, rowsToRemove)
aExtracted = a(rowsToRemove)
aKeepers = a(~logicalIndexes)
a = [10 20 30 40 50 60 70];
indexes = 1 : numel(a);
rowsToRemove = [1, 5];
logicalIndexes = ismember(indexes, rowsToRemove)
aExtracted = a(rowsToRemove)
aKeepers = a(~logicalIndexes)
% Also log what indexes are kept.
keeperIndexes = indexes(~logicalIndexes)
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!