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

4 views (last 30 days)
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?

Accepted Answer

Guillaume
Guillaume on 31 Jan 2019
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))]}))]

More Answers (2)

Ollie A
Ollie A on 30 Jan 2019
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 Comments
Guillaume
Guillaume on 31 Jan 2019
"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 on 31 Jan 2019
"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.

Sign in to comment.


Stephen23
Stephen23 on 31 Jan 2019
Edited: Stephen23 on 31 Jan 2019
>> F = @(v){unique(v,'stable').'};
>> C = accumarray(M(:,1),M(:,2),[],F);
>> C{:}
ans =
3 4
ans =
5 4
ans =
1 7 9
  3 Comments
Stephen23
Stephen23 on 31 Jan 2019
Edited: Stephen23 on 31 Jan 2019
@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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!