How to change consecutive duplicate values, so that they are unique

3 次查看(过去 30 天)
I have an array A = [1,2,2,4,5,5,5,6], and I would like to get B=[1,2,2.1,4,5,5.1,5.2,6]. How to do it? Thanks!
  2 个评论
the cyclist
the cyclist 2023-2-15
A few questions:
  • are the input values guaranteed to be integers?
  • are the duplicate values guaranteed to be next to each other?
  • are you guaranteed to have 9 or few duplicates of a given number?
Jasmine Zhu
Jasmine Zhu 2023-2-15
1. Yes. Integers. 2. Yes, duplicates are next to each other. 3. Yes, a random number less than 9.

请先登录,再进行评论。

采纳的回答

the cyclist
the cyclist 2023-2-15
编辑:the cyclist 2023-2-15
If the answer to all of my question in my above comments are "yes", then
% Input
A = [1,2,2,4,5,5,5,6];
% Algorithm
B = A;
for ib = 2:numel(B)
if B(ib)==floor(B(ib-1))
B(ib) = B(ib-1) + 0.1;
end
end
B
B = 1×8
1.0000 2.0000 2.1000 4.0000 5.0000 5.1000 5.2000 6.0000
  2 个评论
Jasmine Zhu
Jasmine Zhu 2023-2-15
My array has about 2,592,000 elements. How long would it take to loop through?
the cyclist
the cyclist 2023-2-15
tic
% Input
A = [1,2,2,4,5,5,5,6];
A = repmat(A,1,ceil(2.6e6/numel(A)));
% Algorithm
B = A;
for ib = 2:numel(B)
if B(ib)==floor(B(ib-1))
B(ib) = B(ib-1) + 0.1;
end
end
B;
toc
Elapsed time is 0.060725 seconds.
61 milliseconds in this one test.

请先登录,再进行评论。

更多回答(1 个)

John D'Errico
John D'Errico 2023-2-15
编辑:John D'Errico 2023-2-15
I once wrote an unrounding tool, that did something like what you want to do. The goal I chose was to perform a minimal perturbation to the original squence that was consistent with having rounded the initial vector, yet is still monotonic, AND is as smooth as possible.
However, you need to consider if your goal is fully valid. It seems you want to add 0.1 to each replicated element. But how would your plan work for the vector
V = [1 1,repmat(2,1,15),3 3 3 3 3 3 3]
V = 1×24
1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3
The thing is, in the vector V, adding multiples of 0.1 will fail.
Vhat = unround(V)
Vhat = 1×24
1.4012 1.4679 1.5346 1.6013 1.6681 1.7348 1.8015 1.8682 1.9349 2.0016 2.0684 2.1351 2.2018 2.2685 2.3352 2.4019 2.4687 2.5354 2.6021 2.6688 2.7355 2.8022 2.8690 2.9357
plot([V;Vhat]','o-')
No perturbation to V is greater than 0.5.
norm(V - round(Vhat))
ans = 0
You could do something different of course.
Edit: Of curse, since now I know that your vector has 3 million elements in it, I would expect that a tool that calls quadprog will fail anyway. For the future, it would have been good of you to tell us pertinent information like that, as I would not have bothered to answer with this solution.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by