Counting duplicate values in a column

23 views (last 30 days)
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 Comments
Image Analyst
Image Analyst on 24 Dec 2020
Are the letters characters, like 'a', or integer numbers, like 123, or floating point, like 123.456?
ma sd
ma sd on 24 Dec 2020
sorry for the confusion,
the second column contains strings

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 24 Dec 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
.

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!