Counting duplicate values in a column
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
ma sd
le 24 Déc 2020
Réponse apportée : Star Strider
le 24 Déc 2020
Good day,
I have a table with multiple columns that looks like
A=
Num Num_2
-------------------
2 a
3 a
1 a
2 b
6 a
1 c
7 c
I am trying to add a new column that shows the number of duplication of the values in column Num_2 just like this
ans=
Num Num_2 Column_3
---------------------------------
2 a 1
3 a 2
1 a 3
2 b 1
6 a 4
1 c 1
7 c 2
2 commentaires
Image Analyst
le 24 Déc 2020
Are the letters characters, like 'a', or integer numbers, like 123, or floating point, like 123.456?
Réponse acceptée
Star Strider
le 24 Déc 2020
I am not certain how robust this will be for a different problem,. however it works here with the example posted:
A = { 2 'a'
3 'a'
1 'a'
2 'b'
6 'a'
1 'c'
7 'c'};
[UAs,~,ic] = unique(A(:,2)); % Unique Indices Of ‘Num_2’
Tallyc = accumarray(ic, 1, [], @(x){cumsum(x)}); % Cumulative Sums Of Indices In ‘Num_2’
Idxc = accumarray(ic, (1:size(A,1)).', [], @(x){x}); % Their Respective Indices
Tallyv = cell2mat(Tallyc); % Convert From Cell Arrays To Vectors
Idxv = cell2mat(Idxc); % Convert From Cell Arrays To Vectors
T1 = cell2table(A); % Create Table For ‘A’
T1 = [T1, table(Tallyv(Idxv))]; % Create Table For ‘Column_3’
T1.Properties.VariableNames = {'Num','Num_2','Column_3'} % Result
producing:
T1 =
7×3 table
Num Num_2 Column_3
___ _____ ________
2 {'a'} 1
3 {'a'} 2
1 {'a'} 3
2 {'b'} 1
6 {'a'} 4
1 {'c'} 1
7 {'c'} 2
.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Tables 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!