フィルターのクリア

Strings with changing length and cases

3 ビュー (過去 30 日間)
JP
JP 2013 年 6 月 19 日
Hi, Im trying to make the following code work and it just wont seem to do what I want. NOTE - The string length of my variable is changing so for different cases I want a different interval.
Astr = '123456789'
switch Astr
case strcmp(Astr([2:4,5:7]), '234567' )
x = 5
case strcmp(Astr([3:6,6:8]), '789123' )
x = 6
case strcmp(Astr([1:3,4:6]), '912345' )
x = 7
otherwise
x = 8
end
I think it has to do with the way Im defining the string values, it keeps outputting x = 8 (the otherwise case). Please let me know how to fix thanks!

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 6 月 19 日
It's more appropriate to use IF statement
Astr = '123456789'
if isequal(Astr([2:4,5:7]), '234567' )
x = 5
elseif isequal(Astr([3:6,6:8]), '789123' )
x = 6
elseif isequal(Astr([1:3,4:6]), '912345' )
x = 7
else
x = 8
end
  1 件のコメント
JP
JP 2013 年 6 月 19 日
thanks thats perfect =)

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

その他の回答 (2 件)

Iain
Iain 2013 年 6 月 19 日
Assuming that you've shown us "everything". Theres a better way:
x = 8 - (Astr(3) == '2') - 2*(Astr(3) == '7') - 3*(Astr(3) == '3');
  2 件のコメント
JP
JP 2013 年 6 月 19 日
Well I havent shown everything...I was just using this as a simpler example for a more complex code Im working on....
Iain
Iain 2013 年 6 月 19 日
Azzi's solution is correct, but it will be easy to get lost in it, and make logical errors.

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


Jan
Jan 2013 年 6 月 19 日
This case can never happen:
strcmp(Astr([3:6,6:8]), '789123' )
One string has 7 character with a repeated sixth element, while the other string has 6 characters only without a repetition.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by