Unique Values based on 2 Variables

This is a little complicated for me to explain, but I'll try my best. Suppose I have 2 variables, var1 and var2.
var1=[1 2 4]' %Column 1
var2(:,1)=[1 1 1 2 4 4 4]' %Column 1
var2(:,2)=[8 9 2 5 5 1 1]' %Column 2
My goal: For each value in var1, I want to refer to column 1 of var2 and find the unique number in column 2. (Forgive me, but even I find it difficult in explaining this. I will illustrate my objective)
Based on the code excerpt above,
In var1, the 1st value is 1. Compare it to var2 column 1 In var2, row 1-3 contains 1 and I wish to find the unique values in column 2.
(Answer: 8,9,2 when col1's value is 1)
(Answer: 5 when col1's value is 2)
(Answer: 5,1 when col1's value is 4)
Again, I am very sorry for this poor explanation.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 6월 7일

1 개 추천

[a,b] = ismember(var2(:,1),var1);
out = [num2cell(var1), accumarray(b(a),var2(:,2),[],@(x){unique(x)})];

댓글 수: 1

RDG
RDG 2013년 6월 7일
Thanks for the hint. I should be able to refine it from here.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2013년 6월 7일

0 개 추천

Why do you want to hassle with cell arrays instead of regular numerical arrays, which would be a lot simpler?

댓글 수: 3

RDG
RDG 2013년 6월 7일
I was trying to relate to my problem as close as possible. My actual problem is in the form of cell array. But anyway, it's the concept which I'm after, so I edited the question based on your comment.
Image Analyst
Image Analyst 2013년 6월 7일
I don't understand where the 8, 9, and 2 came from. If var1 = 1, this occurs in col1 of var2 in rows 1, 2, and 3. The values in rows 1, 2, and 3 of col2 of var2 are 1 & 2, not 8, 9, and 2.
RDG
RDG 2013년 6월 7일
Aye, sorrryy...I forgot to edit the question.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Language Fundamentals에 대해 자세히 알아보기

태그

질문:

RDG
2013년 6월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by