count string in a cell array

How can I count how many times a pattern of a string /char is presented in a cell array ????
string = 945
cell = {1234, 9456, 9457 }
I want the result to be = 2

1 commentaire

the cyclist
the cyclist le 21 Nov 2019
Modifié(e) : the cyclist le 21 Nov 2019
Are the contents of the cell array numeric (e.g. class "double"), string, or character array?
Similarly, is the variable you named "string" a numeric, a string, or a character array. (Calling a variable "string" or "cell" is a bad idea, because those are MATLAB keywords.)
If one of your cell elements was 9457945, would that count once, or twice, in the total?

Connectez-vous pour commenter.

Réponses (2)

Ridwan Alam
Ridwan Alam le 21 Nov 2019

0 votes

cell = {1234, 9456, 9457 }
strong = 945
count = sum(contains(string(cell),string(strong)))

3 commentaires

the cyclist
the cyclist le 21 Nov 2019
This solution is a good illustration of why "string" is a bad variable name.
Ridwan Alam
Ridwan Alam le 21 Nov 2019
Haha, for sure!
Ridwan Alam
Ridwan Alam le 22 Nov 2019
Modifié(e) : Ridwan Alam le 22 Nov 2019
Dear Collegue,
If you find this solution useful, please accept the answer.
If there is something wrong, please let me know as well.
Thanks!!

Connectez-vous pour commenter.

Stephen23
Stephen23 le 21 Nov 2019

0 votes

>> S = '945';
>> C = {'1234', '9456', '9457'};
>> nnz(~cellfun(@isempty,strfind(C,S)))
ans = 2

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Question posée :

le 21 Nov 2019

Modifié(e) :

le 22 Nov 2019

Community Treasure Hunt

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

Start Hunting!

Translated by