How to delete repeated values in a vector as well as values in its corresponding vector
89 次查看(过去 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
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!