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

조회 수: 14 (최근 30일)
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

채택된 답변

Guillaume
Guillaume 2018년 7월 3일
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
Colin Lynch
Colin Lynch 2018년 7월 3일
I am simply amazed you thought of that so quickly! Thank you so much!!!
OCDER
OCDER 2018년 7월 3일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by