2

I have a Nx4 cell array in Matlab which looks something like this:

id1 word11 word12 word13
....
id2 word21 word22 word32
....   
idN wordN1 wordN2 wordN3

where each of the four columns holds a string and the second column (word11... wordN1) can have duplicate values. I want to get another cell array but with unique rows according to the second column. so in the previous example if word21 was the same as wordN1, the resulting array should have the following two rows only (doesn't matter which row of the duplicates gets chosen):

id1 word11 word12 word13    
....    
idN wordN1 wordN2 wordN3

I tried unique(cellArray{2}) but it only returns the second column with the unique values and I want the whole row. How can I do this?

Thanks

1
  • Hi, given that this is your first question, I just thought I'd let you know that if you feel I have answered the question, then you should click the tick-mark next to my answer. If you are not satisfied with my answer, then let me know and I'll attempt to improve it. Cheers. Commented Sep 25, 2012 at 2:41

1 Answer 1

3

I believe the following should do it:

Z = {'a', 'b'; 'a', 'c'; 'a', 'c'; 'a', 'd'; 'a', 'b'};
[~, I1] = unique(Z(:, 2));
I1 = sort(I1);
Soln = Z(I1, :);

An explanation? I use the optional additional arguments of unique to obtain the indices of unique elements in the second column. I then sort this index so that we can preserve the original ordering of Z. Finally, I retrieve the rows of Z indexed by I1.

Note, it is a bit unintuitive that the sort actually preserves the original ordering rather than sorting it :-) The reason is that I1 contains the row indices of the unique elements. Thus sorting it returns the row indices in order from smallest to largest, thus preserving the original order in Z.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Note that the second tilde in the unique call is unneccessary: [~,I1] = unique(Z(:,2)); will suffice
@RodyOldenhuis Huh, interesting, you are correct. I was going off the official matlab documentation here, where the function syntax indicates it has either 1 or 3 outputs. Anyway, I've edited my answer, thanks Rody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.