How to make a unique vector
조회 수: 3 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (4개)
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
EDIT: Credit goes to gnovice at stackoverflow: http://stackoverflow.com/questions/3065387/how-can-i-remove-duplicates-in-an-array-but-keep-the-same-order
댓글 수: 0
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
댓글 수: 0
Yingquan Li
2011년 7월 6일
댓글 수: 1
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 Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!