Counting duplicate values in a column

6 Ansichten (letzte 30 Tage)
ma sd
ma sd am 24 Dez. 2020
Beantwortet: Star Strider am 24 Dez. 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 Kommentare
Image Analyst
Image Analyst am 24 Dez. 2020
Are the letters characters, like 'a', or integer numbers, like 123, or floating point, like 123.456?
ma sd
ma sd am 24 Dez. 2020
sorry for the confusion,
the second column contains strings

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Star Strider
Star Strider am 24 Dez. 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
.

Weitere Antworten (0)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by