Effacer les filtres
Effacer les filtres

How to delete repeated values in a vector as well as values in its corresponding vector

96 vues (au cours des 30 derniers jours)
Hello there!
I am attempting to delete repeated values in a vector and then delete values in a vector of the exact same length at the same index. For instance, say I have the following two vectors:
n_vector = [1 2 3 5 5 5 5 7 6 6];
t_vector = [1 2 3 4 5 6 7 8 9 10];
The n vector has the repeating values 5 and 6, so I need a bit of code that transforms these vectors into this:
n_vector = [1 2 3 5 7 6];
t_vector = [1 2 3 4 8 9];
I tried to do this with the following code, however it doesn't work if values repeat more than twice:
u = 1;
while u > 0
for i = 1:length(n_vector)
if length(n_vector(i:end)) > 1
if n_vector(i) == n_vector(i+1)
n_vector(i+1) = [];
t_vector(i+1) = [];
u = 1;
else
u = 0;
end
elseif length(n_vector) == 1
u = 0;
else
break
end
end
end
Is there a way that I can fix this code so it can delete values no matter how many times it repeats, or do I need to do try something else all together?
Sincerely, Colin

Réponse acceptée

Guillaume
Guillaume le 3 Juil 2018
I don't know about your code, but this will be a lot more efficient than what you're trying to do:
repeats = diff(n_vector) == 0;
n_vector(repeats) = [];
t_vector(repeats) = [];
%all done!
  2 commentaires
Colin Lynch
Colin Lynch le 3 Juil 2018
I am simply amazed you thought of that so quickly! Thank you so much!!!
OCDER
OCDER le 3 Juil 2018
Here's a variation of the Answer that's ~3.5 faster. In Matlab, deleting elements from a vector tends to be slower than taking a subset of a vector.
a = sort(randi(6, 1, 1E7));
b = 1:1E7;
n_vector = a; t_vector = b;
tic
repeats = [1 diff(n_vector)] == 0;
n_vector(repeats) = [];
t_vector(repeats) = [];
toc % 0.4392 s
n_vector = a; t_vector = b;
tic
nonrepeats = [1 diff(n_vector)] ~= 0;
n_vector = n_vector(nonrepeats);
t_vector = t_vector(nonrepeats);
toc % 0.1383 s

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by