フィルターのクリア

Unique Function based on 2 columns [Instead of rows]

1 回表示 (過去 30 日間)
RDG
RDG 2013 年 4 月 7 日
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 件のコメント
Cedric
Cedric 2013 年 4 月 7 日
See the edit in my answer.
Cedric
Cedric 2013 年 4 月 8 日
See 2nd edit.

サインインしてコメントする。

採用された回答

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)))))
  1 件のコメント
RDG
RDG 2013 年 4 月 8 日
What if I want the value to return '4'? [Since there are 4 duplicates]

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by