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

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

请先登录,再进行评论。

类别

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