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

3 vues (au cours des 30 derniers jours)
MJ
MJ le 30 Jan 2019
Commenté : MJ le 31 Jan 2019
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?

Réponse acceptée

Guillaume
Guillaume le 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))]}))]
  1 commentaire
MJ
MJ le 31 Jan 2019
This code works perfect, thank you very much for your time!

Connectez-vous pour commenter.

Plus de réponses (2)

Ollie A
Ollie A le 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 commentaires
Guillaume
Guillaume le 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 le 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.

Connectez-vous pour commenter.


Stephen23
Stephen23 le 31 Jan 2019
Modifié(e) : Stephen23 le 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 commentaires
Stephen23
Stephen23 le 31 Jan 2019
Modifié(e) : Stephen23 le 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
MJ
MJ le 31 Jan 2019
thank you very much

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by