Remove array elements but also store the element indices that were not removed
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Mohd Aaquib Khan
il 23 Nov 2022
Commentato: Image Analyst
il 23 Nov 2022
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.
0 Commenti
Risposta accettata
Steven Lord
il 23 Nov 2022
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)
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
a1(u) = [] % Then delete them from the orignnal vector
Più risposte (1)
Image Analyst
il 23 Nov 2022
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 Commenti
Image Analyst
il 23 Nov 2022
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)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!