How to do an 'if loop' that finds if a column vector contains a string
7 views (last 30 days)
Show older comments
To put it in words, how would you do
if y(:,i) contains ('A' and 'B') or ('C' and 'D')
1 Comment
Answers (2)
Geoff Hayes
on 4 Jul 2015
str = y(:,k)'; % ensure that the string is a row
if (~isempty(strfind(str,'A')) && ~isempty(strfind(str,'B'))) || ...
(~isempty(strfind(str,'C')) && ~isempty(strfind(str,'D')))
% do something
end
Note how k is used instead of i (which MATLAB uses as a representation of the imaginary number). We first need to convert the string to a row of characters so that we can use strfind to search for what we are looking for. If the result returned from this call is empty, then we know that the characters don't appear in the string. That's why we use the ~isempty(...).
If you wish to use regexp, then you could try something similar
str = y(:,k)';
if (~isempty(regexp(str,'[A]')) && ~isempty(regexp(str,'[B]'))) || ...
(~isempty(regexp(str,'[C]')) && ~isempty(regexp(str,'[D]')))
% do something
end
(There may be a better way to make use of regexp so that the above code is simplified.)
2 Comments
Geoff Hayes
on 8 Jul 2015
Joey - given your example, it would appear that your input array is a cell array. Is this the case? Because that would mean that the code would have to be modified to handle that. For example,
data = {'AH' 'QS'
'4C' '3C'
'3D' 'AD'
'2S' '5D'
'TD' 'AS' };
cards = char(data(:,1));
value = cards(:,1)';
suit = cards(:,2)';
if (~isempty(strfind(str,'A')) && ~isempty(strfind(suit,'H')))
fprintf('you have the ace of hearts!\n');
end
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!