Unique numbers, not ordered
2 views (last 30 days)
Show older comments
I have three matrices:
X1 = [1 23 36 45 47 2]'
X2 = [1 36 47 2 6]'
X3 = [1 22 23 47 2 4]'
I want to end up with a matrix like this:
X = [1 22 23 36 45 47 2 4 6]
I tried using this code:
unique([X1;X2;X3],'stable')
And this came out:
X = [1 23 36 45 47 2 6 22 4]
The numbers go up to 47 and then they go from low to high again. When the numbers go up again they are all unique numbers, so numbers that didn't occur the first time when the numbers went up.
X1 = [1 23 36 45 47 ** 2]'
X2 = [1 36 47 ** 2 6]'
X3 = [1 22 23 47 ** 2 4]'
I want to get the unique numbers bofore the drop, indicated with **, and after the drop.
X_before = [1 22 23 36 45 47]'
X_after = [2 4 6]
And then I can get the matrix I want:
X = [X_before; X_after]
= [1 22 23 36 45 47 2 4 6]
4 Comments
Stephen23
on 4 Jun 2021
@Dylan den Hartog: what should happen if:
- the maximum value occurs twice (or more)?
- the maximum does not occur in one (or more) of the vectors?
Answers (1)
the cyclist
on 4 Jun 2021
I believe this does what you want:
X1 = [1 23 36 45 47 2]';
X2 = [1 36 47 2 6 ]';
X3 = [1 22 23 47 2 4]';
peak1 = find(diff(X1)<0,1);
peak2 = find(diff(X2)<0,1);
peak3 = find(diff(X3)<0,1);
X_u = unique([X1(1:peak1); X2(1:peak2); X3(1:peak3)])
X_d = unique([X1(peak1+1:end); X2(peak2+1:end); X3(peak3+1:end)])
X_sort = [X_u; X_d]
This will break if the last value of any of the original vectors is the max, but that is easily fixed up.
2 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!