Comparing Rows of Char Array to String

Hi everyone,
I have an 8x3 char array that looks like the following
Wed
Wed
Wed
Wed
Wed
Wed
Wed
Sat
I need to compare it to a string to perform one action when the day is Wednesday (or Wed) and a different action when the day is Saturday (or Sat). For i = 1:8, a loop runs to put the output of this if statement into a numeric vector.
How can I go about properly comparing each row of the char array to a string ('Wed' or 'Sat')?
Thanks in advance!

回答 (1 件)

Guillaume
Guillaume 2015 年 2 月 11 日

1 投票

Use the second output of ismember with the 'rows' option:
c = ['Wed'; 'Wed'; 'Fri'; 'Wed'; 'Sat'];
[~, actionnumber] = ismember(c, ['Wed'; 'Sat'], 'rows')

4 件のコメント

Justin Duval
Justin Duval 2015 年 2 月 11 日
Thanks for the response. What I ended up doing is the following:
if dayname(i,1:3) == 'Wed'
do something
else
do something else
end
It seems to be functioning fine...do you think there's anything wrong with how I've approached it?
Guillaume
Guillaume 2015 年 2 月 11 日
There's nothing particularly wrong about your approach which uses a loop. Depending on how similar the actions are, I would probably personally use arrayfun and function handles to dispatch to each actions, but it's more a matter of style.
One nitpick is that you shouldn't be using == to compare string, strcmp is more robust:
if strcmp(dayname(i, :), 'Wed')
Additionally, knowing that programs can grow, rather than if ... else, I'd use switch ... case statements. It's much easier to add actions in the future. As an added bonus, switch use strcmp when given strings:
switch dayname(i, :)
case 'Wed'
%do someting
case 'Sat'
%do something
end
I don't really like the fact that your else does not explictly state it applies to 'Sat'. What if your string ends up being 'Thu'. Again the case is more explicit.
Image Analyst
Image Analyst 2015 年 2 月 11 日
Even more robustness can be gained by casting the day to lower case if you don't really care about the case of the letters. Or you could use strcmpi(). If you don't care about case then it's most robust if your code works regardless if they capitalized the day or not.
if strcmp(lower(dayname(i, :)), 'wed')
if strcmpi(dayname(i, :), 'Wed')
switch lower(dayname(i, :))
case 'wed'
Justin Duval
Justin Duval 2015 年 2 月 11 日
Thanks for the extra input. My code does cover other days of the week as well, I was just including the simplest case based on the set of data in my original post as it was all I needed to convey my problem.
I will swap out the == operator for strcmp, and I will look into switch case statements as well, they look nice.
Thanks again!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2015 年 2 月 11 日

コメント済み:

2015 年 2 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by