Mark Hughes
Mark Hughes

Reputation: 245

Searching an array for a variable

How would I check if the string value of a specific variable is present in an array? I know strcmp and ismember are options, but how would I adapt these so they use the value of a variable to search in an array, as opposed to me typing in the string I want to search for. So my code will look something like:

C1 = {'red' 'yellow'};
C2 = {'green' 'blue'};
fn = 'blue';  

%Comparison function here

if % fn is present in C1
    c = 'm'

Thanks

Upvotes: 1

Views: 70

Answers (2)

Acorbe
Acorbe

Reputation: 8391

I did not understand what is wrong with strcmp, thus I am not sure I understood your question. Consider this

if any( strcmp(fn,C2) ) 
   disp('OK!')    % // OR  c = 'm'
end


OK!

Upvotes: 4

Shai
Shai

Reputation: 114796

How about

if any( cellfun( @(x) isequal(x, fn), C1 ) )
   c = 'm';
end

I believe you may also use regexp.

Upvotes: 2

Related Questions