How to make a unique vector

4 次查看(过去 30 天)
Yingquan Li
Yingquan Li 2011-7-6
Hello. Given this vector:
a = [22 20 21 20 24 25 26 22]
I want it to return
[22 20 21 24 25 26]
The unique function works but, I don't want the array to increase in order. I'm new and thank you in advance.

回答(4 个)

D
D 2011-7-6
Also, from stackoverflow (I don't remember where, but if I find the post, I'll link it):
[junk,index] = unique(a,'first'); % removes non-unique, saves order in "index"
a = a(sort(index)); % sorts according to index

Oleg Komarov
Oleg Komarov 2011-7-6

Paulo Silva
Paulo Silva 2011-7-6
a = [22 20 21 20 24 25 26 22] %your vector
b=unique(a); %get the unique ones
d=perms(b); %get all possible permutations of the vector values
%sort the rows so we can avoid the first one 20 21 ...
d=sortrows(d); %sort the rows
p=randi([2 size(d,1)]); %get a random row of the array
%you can also avoid the last one if you want by using the next line instead
%p=randi([2 size(d,1)-1]);
v=d(p,:) %get all the values from the row selected

Yingquan Li
Yingquan Li 2011-7-6
Hey guys, I tried: for i = 1:length(a) for j = 2:length(a) if (a(i) == a(j)) a(j) = [] end end end
There was an error. I don't see what's wrong.
  1 个评论
Sean de Wolski
Sean de Wolski 2011-7-6
well you keep making a smaller by removing elements but the for-loop wants to go to it's original length.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by