Counting duplicate values in a column

6 vues (au cours des 30 derniers jours)
ma sd
ma sd 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
Image Analyst le 24 Déc 2020
Are the letters characters, like 'a', or integer numbers, like 123, or floating point, like 123.456?
ma sd
ma sd le 24 Déc 2020
sorry for the confusion,
the second column contains strings

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
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
.

Plus de réponses (0)

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by