MATLAB: Counting duplicate values in a column

columncountduplicateMATLABtablevalue

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

Best Answer

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
.