Unique Function based on 2 columns [Instead of rows]

2 次查看(过去 30 天)
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.

采纳的回答

Cedric
Cedric 2013-4-7
编辑:Cedric 2013-4-8
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 个评论
RDG
RDG 2013-4-8
Thank you Cedric, but it seems that my question was a poorly structured.
RDG
RDG 2013-4-8
Thanks again Cedric for including in the explanation. Been having a hard time translating my ideas into code.

请先登录,再进行评论。

更多回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-4-7
编辑:Azzi Abdelmalek 2013-4-7
b=a{1};
out=all(~(any(diff(b(:,3:4)))))

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by