# Count the number of occurrences in a string vector

12 views (last 30 days)
buhmatlab on 7 Apr 2020
Edited: Andrei Bobrov on 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!

Andrei Bobrov on 7 Apr 2020
Edited: Andrei Bobrov on 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.
buhmatlab on 7 Apr 2020
This works perfectly! I wonder how long it would have taken for me to figure this out...
THANK YOU!!!
{"ft_lang_label":"__label__en","ft_lang_prob":0.73428476,"math_prob":0.84449434,"size":1123,"snap":"2023-14-2023-23","text_gpt3_token_len":368,"char_repetition_ratio":0.08757819,"word_repetition_ratio":0.042105265,"special_character_ratio":0.33748886,"punctuation_ratio":0.20833333,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9970723,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-06-08T05:28:31Z\",\"WARC-Record-ID\":\"<urn:uuid:264332a7-7cac-4447-affa-e1c51a8d3daf>\",\"Content-Length\":\"123407\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:2b959b18-e8cb-4890-82dc-a4af7ccf1125>\",\"WARC-Concurrent-To\":\"<urn:uuid:64e8121e-c01a-411f-855c-c361a3165412>\",\"WARC-IP-Address\":\"104.92.226.189\",\"WARC-Target-URI\":\"https://es.mathworks.com/matlabcentral/answers/516045-count-the-number-of-occurrences-in-a-string-vector\",\"WARC-Payload-Digest\":\"sha1:2ZZTRMWO3FXUSZUJO6BO7OKMN27QQS6Q\",\"WARC-Block-Digest\":\"sha1:4ERGRBB4JSCK2RGNWWH2S5NBL7EUWW3D\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224654097.42_warc_CC-MAIN-20230608035801-20230608065801-00069.warc.gz\"}"}