MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by pietro on 11 Jul 2014

Hi all,

I need to set a cell as pattern for strfind without using a for. Here an example

a={'1','2','3'}; b={'1','2'}; c=strfind(a,b)

c=[1 1 [] ];

thanks

cheers

Answer by Image Analyst on 12 Jul 2014

Edited by Image Analyst on 12 Jul 2014

Accepted answer

Here is a simple, easy to understand way that will work:

clc; % Clear command window. % Initialize variables. a={'1','21','3'}; b={'2','1'}; % Initialize results. % Let's use a simple numerical array rather than a cell array! c = zeros(1, length(a)); % Scan each element of "a" for all the elements of "b". for k = 1 : length(a) for colb = 1 : length(b) if ismember(b{colb}, a{k}) c(k) = 1; break; end end end % Print out to command window. c

Answer by Jos (10584) on 11 Jul 2014

% implicit for with CELLFUN c = cellfun(@(x) strfind(x,b), a, 'un', 0)

Answer by Titus Edelhofer on 11 Jul 2014

Hi,

not exactly the same result but similar:

ismember(a, b)

Titus

Answer by Chris E. on 11 Jul 2014

Hello! Well I think this answers your question, it does not have a for loop, however it uses "ismember" rather then 'strfind', but I think the output is the same as what you want.

a={'1','2','3'} b={'1','2'} val = ismember(a,b) val(val == 0)=[] c = val

Hope that helps!

Answer by Jos (10584) on 11 Jul 2014

Then please explain the relationship between a,b,and c. Why is c{2} equal to 1?

## 5 Comments

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/141451#comment_225168

Why not having a for loop???

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/141451#comment_225177

I would prefer a faster and more elegant solution but in case it doesn't exist, I'm up for a loop to.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/141451#comment_225181

Elegant solutions aren't always faster; they are easier to read and save space and coding, I agree on that, but if performance is the issue, you have to test with and without the loop with the profiler (or tic toc). I was just trying to understand what the logic behind the question is.

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/141451#comment_225296

What about this case:

Do you consider that the 1 and the 2 are found/matched, or not? They are not in the

same locations, but both are in both arrays.Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/141451#comment_225315

the output should be {[1],[1],[]}.