user3439050
user3439050

Reputation: 37

How to find the occurences of the elements of first cell array in second cell array in MATLAB?

I have two cell arrays:

A={'abc','pai','abd','pa/n/v/d'}

B={'pai-pro','abc','pai','abd/','abd','pa/n/v/d','abd-','pa/n/v/d','pai-pro'}

I need a code to find the occurrence of the elements of A in B. Such that the output would be:

'abc' = 1

'pai' = 3

'abd' = 3

'pa/n/v/d' = 2

Upvotes: 0

Views: 37

Answers (2)

Alekos
Alekos

Reputation: 11

This will do it:

for i = 1:length(A)
   sum(cell2mat(strfind(cellstr(B),A{i})))
end

Upvotes: 1

Dinesh
Dinesh

Reputation: 2204

For each element of A, you can do the following to get its occurrence in B

[isPresent, index] = ismember(A{1}, B)

The index will contain the location of the element A{i} in B if it is present indicated by the isPresent variable.

Upvotes: 0

Related Questions