How to delete repeated values in a vector as well as values in its corresponding vector
130 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Colin Lynch
el 3 de Jul. de 2018
Comentada: OCDER
el 3 de Jul. de 2018
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
0 comentarios
Respuesta aceptada
Guillaume
el 3 de Jul. de 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 comentarios
OCDER
el 3 de Jul. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!