Unique Function based on 2 columns [Instead of rows]

2 vues (au cours des 30 derniers jours)
RDG
RDG le 7 Avr 2013
Suppose, I have a cell array, a, with contents as such:
a{1}=[1 3 4 5;
3 3 4 5;
5 5 4 5
2 4 2 6;
6 5 2 6
7 2 3 1;]
How can I apply the 'unique' function on 2 columns [column 3 and 4] such that they will return the value '3' and '2'. [Since there are 3 duplicates for the pair 4,5 and 2 duplicates for the pair 2,6.]
Any hint is greatly appreciated.
  2 commentaires
Cedric
Cedric le 7 Avr 2013
See the edit in my answer.
Cedric
Cedric le 8 Avr 2013
See 2nd edit.

Connectez-vous pour commenter.

Réponse acceptée

Cedric
Cedric le 7 Avr 2013
Modifié(e) : Cedric le 8 Avr 2013
NEW ANSWER AFTER 2ND EDIT
You could do it as follows (you might want to fine tune it):
diff(find([true; any(diff(a{1}(:,3:4)),2); true]))
To understand this solution, evaluate it by part:
>> a{1}(:,3:4) % Index col 3 and 4.
ans =
4 5
4 5
4 5
2 6
2 6
3 1
>> diff(a{1}(:,3:4)) % Difference between rows in col 3 and 4.
ans =
0 0
0 0
-2 1
0 0
1 -5
>> any(diff(a{1}(:,3:4)),2) % Flag rows were there is a diff in either col.
ans =
0
0
1
0
1
>> [true; any(diff(a{1}(:,3:4)),2); true] % Add flags for boundaries.
ans =
1
0
0
1
0
1
1
>> find([true; any(diff(a{1}(:,3:4)),2); true]) % Get positions of all flags.
ans =
1
4
6
7
Finally, compute positions differences.
>> diff(find([true; any(diff(a{1}(:,3:4)),2); true]))
ans =
3
2
1
which give you the size (in terms of number of rows) of each block of similar cols 3 and 4.
FORMER ANSWER
>> [u, ia] = unique(a{1}(:,3:4), 'rows', 'stable')
u =
4 5
ia =
1
The flag 'rows' tests rows uniqueness (taking all columns into account). So here it seems that you want to pass columns 3 and 4 of array a{1} to UNIQUE, using the 'rows' flag. The stable flag makes unique return the first occurrence instead of the last in this case.
If you wanted to operate on columns (for all rows), you could pass a subset of the transpose of a{1} to UNIQUE.
EDIT (after you edited the question): remove the 'stable' flag if you want 4.
  2 commentaires
RDG
RDG le 8 Avr 2013
Thank you Cedric, but it seems that my question was a poorly structured.
RDG
RDG le 8 Avr 2013
Thanks again Cedric for including in the explanation. Been having a hard time translating my ideas into code.

Connectez-vous pour commenter.

Plus de réponses (1)

Azzi Abdelmalek
Azzi Abdelmalek le 7 Avr 2013
Modifié(e) : Azzi Abdelmalek le 7 Avr 2013
b=a{1};
out=all(~(any(diff(b(:,3:4)))))
  1 commentaire
RDG
RDG le 8 Avr 2013
What if I want the value to return '4'? [Since there are 4 duplicates]

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by