Finding the set of unique values for another set of unique values

조회 수: 6 (최근 30일)
MJ
MJ 2019년 1월 30일
댓글: MJ 2019년 1월 31일
hi everyone,
i have a dataset of which the first column contains buyers ID', the second column has a certin index, i need an output that shows what are the indeces associated with each unique buyer ID, for example: if i have a set like this:
1 3
1 3
1 4
2 5
2 4
3 1
3 7
3 7
3 7
3 9
M = [ 1,3;1,3;1,4;2,5;2,4;3,1;3,7;3,7;3,7;3,9];
i want an output in the form of
1 [3 4]
2 [5 4]
3 [1 7 9]
can anyone please help me?

채택된 답변

Guillaume
Guillaume 2019년 1월 31일
i am looking for an array type [...] can it be filled with NaN or zeros?
NaN is probably wiser.
M = [ 1,3;1,3;1,4;2,5;2,4;3,1;3,7;3,7;3,7;3,9];
Mdedup = unique(M, 'rows'); %remove duplicate rows.
[id, ~, sub] = unique(Mdedup(:, 1)); %list of unique IDs and corresponding location
maxcount = max(accumarray(sub, 1)); %get max of histogram of IDs = width of matrix to create
result = [id, cell2mat(accumarray(sub, Mdedup(:, 2), [], @(v) {[v.', nan(1, maxcount - numel(v))]}))]

추가 답변 (2개)

Ollie A
Ollie A 2019년 1월 30일
This should do the trick:
M = [ 1,2;1,3;1,2;2,4;2,4;2,5]; % Your matrix
u = unique(M(:,1));
for x = 1:length(u)
N{x} = unique(M(M(:,1)==u(x),2));
end
T = table(u,N'); % Output as table
The output is a table, which displays the data in the way you requested.
  댓글 수: 5
Guillaume
Guillaume 2019년 1월 31일
"I want to separate the values in the same cell to two different cells"
A table/cell array/matrix is always rectangular. In the case where there's less elements in a row than others what do you want to put in the missing columns?
With your original example, the ouput would be
1 3 4 x
2 5 4 x
3 1 7 9
What should x be?
Also, what type of output are you looking for (matrix? cell array? table?)
MJ
MJ 2019년 1월 31일
"what do you want to put in the missing columns?"
can it be filled with NaN or zeros?
"what type of output are you looking for (matrix? cell array? table?)"
i am looking for an array type, i want to use the output numbers in other calculations.

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


Stephen23
Stephen23 2019년 1월 31일
편집: Stephen23 2019년 1월 31일
>> F = @(v){unique(v,'stable').'};
>> C = accumarray(M(:,1),M(:,2),[],F);
>> C{:}
ans =
3 4
ans =
5 4
ans =
1 7 9
  댓글 수: 3
Stephen23
Stephen23 2019년 1월 31일
편집: Stephen23 2019년 1월 31일
@mohammad aljarrah: one very easy solution is to download padcat:
and simply use it like this:
>> padcat(C{:})
ans =
3 4 NaN
5 4 NaN
1 7 9
MJ
MJ 2019년 1월 31일
thank you very much

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by