# Count the number of occurrences in a string vector

9 visualizzazioni (ultimi 30 giorni)
buhmatlab il 7 Apr 2020
Modificato: Andrei Bobrov il 7 Apr 2020
Hi,
I'm relatively new to Matlab because I only used Excel so far. For my project I used the COUNTIFS function and I'm wondering how to do this in Matlab.
Say I've got a column vector 300x1:
I want to create a vector of the same size that counts and sums up each entry.
Example:
If my entries are A;A;B;A;B;B;C;A;C the new vector should look like: 1;2;1;3;2;3;1;4;2
Thank you so much!
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Andrei Bobrov il 7 Apr 2020
Modificato: Andrei Bobrov il 7 Apr 2020
s = string({'A';'A';'B';'A';'B';'B';'C';'A';'C'});
out = zeros(numel(s),1);
[~,~,c] = unique(s);
for i = 1:max(c)
lo = c == i;
out(lo) = 1:sum(lo);
end
or
[~,~,c] = unique(s);
z = c == (1:max(c)); % or use here: z = bsxfun(@eq,c,1:max(c));
out = sum(cumsum(z).*z,2);
I'm use R2016b.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
buhmatlab il 7 Apr 2020
This works perfectly! I wonder how long it would have taken for me to figure this out...
THANK YOU!!!

Accedi per commentare.

### Categorie

Scopri di più su String Parsing in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by