How can I remove duplicates in an array but keep the same order?
-
I have this cell array in MATLAB: y = { 'd' 'f' 'a' 'g' 'g' 'a' 'w' 'h'} I use unique(y) to get rid of the duplicates but it rearranges the strings in alphabetical order: >> unique(y) ans = 'a' 'd' 'f' 'g' 'h' 'w' I want to remove the duplicates but keep the same order. I know I could write a function do do this but was wondering if there was a simpler way using unique to remove duplicates while keeping the same order just with the duplicates removed. I want it to return this: >> unique(y) ans = 'd' 'f' 'a' 'g' 'w' 'h'
-
Answer:
Here's one solution that uses some additional input and output arguments that http://www.mathworks.com/access/helpdesk/help/techdoc/ref/unique.html has: >> y = { 'd' 'f' 'a' 'g' 'g' 'a' 'w' 'h'}; %# Sample data >> [junk,index] = unique(y,'first'); %# Capture the index, ignore junk >> y(sort(index)) %# Index y with the sorted index ans = 'd' 'f' 'a' 'g' 'w' 'h'
Ben Fossen at Stack Overflow Visit the source
Other answers
If you look at the documentation for http://www.mathworks.com/access/helpdesk/help/techdoc/ref/unique.html, there's the option to return an index along with the sorted array. You can specify whether you want the first or last occurrence of a number to be returned to the index as well. For example: a=[5, 3, 4, 2, 1, 5, 4]; [b,order]=unique(a,'first') returns b=[1, 2, 3, 4, 5] and m=[5, 4, 2, 3, 1] You can sort your order array and store the index next [~,index]=sort(order) %# use a throw-away variable instead of ~ for older versions and finally re-index b b=b(index)
Doresoom
Related Q & A:
- How can I remove duplicate Objects from array of Objects in javascript?Best solution by Stack Overflow
- How can I remove an element in a repeated list?Best solution by Stack Overflow
- How can I remove hyperlink?Best solution by Yahoo! Answers
- How can I remove a casset tape from my car player? It is a 2003 Hyundai Sonota. Does anyone else this problem?Best solution by Yahoo! Answers
- How can I remove names from my messenger list?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.