필터 지우기
필터 지우기

How to do an 'if loop' that finds if a column vector contains a string

조회 수: 9 (최근 30일)
Joey
Joey 2015년 7월 4일
댓글: Geoff Hayes 2015년 7월 8일
To put it in words, how would you do
if y(:,i) contains ('A' and 'B') or ('C' and 'D')
  댓글 수: 1
Jan
Jan 2015년 7월 4일
There are no "if-loops" in any programming language. if is simply not a loop.

댓글을 달려면 로그인하십시오.

답변 (2개)

Jan
Jan 2015년 7월 4일
편집: Jan 2015년 7월 4일
A bold guess:
if all(ismember('AB', y(:,i))) || all(ismember('CD', y(:, i)))

Geoff Hayes
Geoff Hayes 2015년 7월 4일
Joey - consider using strfind or regexp. If the former, then you could try
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
Joey
Joey 2015년 7월 5일
nothing seems to be working so far. What I have is a 5x10000 matrix y that is supposed to represent 5 card poker hands. The first character is the card and the second character is the suit. It looks like
AH QS ...
4C 3C ...
3D AD ...
2S 5D ...
TD AS ...
What I want to do is find how many hands have a straight in them, so I need to search each column for an A,2,3,4,5 or 2,3,4,5,6, or 3,4,5,6,7 and so on.
Geoff Hayes
Geoff Hayes 2015년 7월 8일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by