Remove array elements but also store the element indices that were not removed

2 ビュー (過去 30 日間)
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.

採用された回答

Steven Lord
Steven Lord 2022 年 11 月 23 日
Do you want the indices or the elements that weren't deleted?
a = ["a", "b", "c", "d", "e" ,"f"];
u = [1 5];
indToKeep = setdiff(1:numel(a), u)
indToKeep = 1×4
2 3 4 6
I'm going to make a copy of a so you can compare the original with the modified copy.
a1 = a;
deletedElements = a1(u) % Extract elements 1 and 5 first
deletedElements = 1×2 string array
"a" "e"
a1(u) = [] % Then delete them from the orignnal vector
a1 = 1×4 string array
"b" "c" "d" "f"
  1 件のコメント
Mohd Aaquib Khan
Mohd Aaquib Khan 2022 年 11 月 23 日
thank you, I will accept this after some time,
Actually I am currently using the same logic using setdiff(). Was just exploring if there were some easier,shorter ways to do it. Especially using '~'
Thanks again

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 11 月 23 日
There are several ways. Here are two:
a = ["a", "b", "c", "d", "e" ,"f"]
a = 1×6 string array
"a" "b" "c" "d" "e" "f"
rowsToRemove = [1, 5];
aExtracted = a(rowsToRemove)
aExtracted = 1×2 string array
"a" "e"
aKept = setdiff(a, aExtracted)
aKept = 1×4 string array
"b" "c" "d" "f"
% Another way
aKept2 = a; % Initialize
aKept2(rowsToRemove) = []
aKept2 = 1×4 string array
"b" "c" "d" "f"
  3 件のコメント
Mohd Aaquib Khan
Mohd Aaquib Khan 2022 年 11 月 23 日
[] is best for deleting but I also need the indices that were not removed as mentioned in the question ([2 3 4 6] is the primary output that I desire). It is important because I want to assemble many matrices to a bigger matrix, thats why I wanted a simpler one line solution but I guess setdiff() is the only easy way which Steven showed and I was already using that.
so basically if
a = [10 20 30 40 50 60 70];
entryIndexToRemove = [1, 5];
then I want ExtractedIndices = [2, 3, 4, 6, 7] as the answer
which is done below using
setdiff( 1:length(a) , entryIndexToRemove)
ans = 1×5
2 3 4 6 7
Image Analyst
Image Analyst 2022 年 11 月 23 日
a = [10 20 30 40 50 60 70];
indexes = 1 : numel(a);
rowsToRemove = [1, 5];
logicalIndexes = ismember(indexes, rowsToRemove)
logicalIndexes = 1×7 logical array
1 0 0 0 1 0 0
aExtracted = a(rowsToRemove)
aExtracted = 1×2
10 50
aKeepers = a(~logicalIndexes)
aKeepers = 1×5
20 30 40 60 70
% Also log what indexes are kept.
keeperIndexes = indexes(~logicalIndexes)
keeperIndexes = 1×5
2 3 4 6 7

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by