How can strings be used in an if loop?

38 ビュー (過去 30 日間)
Nathan Costin
Nathan Costin 2016 年 7 月 12 日
回答済み: Tom Hawkins 2018 年 11 月 14 日
I am trying to use a string to create an if loop for a programme that analyses an image. I'm getting this string from a prompt then just placing in a test to see if my code has worked. Can anyone give me any pointers as to how to get this to work? My code is attached
prompt1 = 'Would you like to remove edge effects (Y/N)?'
ans1 = input(prompt1)
if ans1 = 'Y'
x = 5*5
elseif ans1 = 'N'
x = 5/5
end

採用された回答

the cyclist
the cyclist 2016 年 7 月 12 日
編集済み: the cyclist 2016 年 7 月 12 日
prompt1 = 'Would you like to remove edge effects (Y/N)?';
ans1 = input(prompt1,'s');
if strcmpi(ans1,'y')
x = 5*5
elseif strcmpi(ans1,'n')
x = 5/5
end
  1 件のコメント
Nathan Costin
Nathan Costin 2016 年 7 月 12 日
thank you!

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

その他の回答 (2 件)

Image Analyst
Image Analyst 2016 年 7 月 12 日
You'd need to use ans1 == 'Y' (two equal signs) or else use the string compare function strcmpi(ans1, 'Y').

Tom Hawkins
Tom Hawkins 2018 年 11 月 14 日
Alternatively…
prompt1 = 'Would you like to remove edge effects (Y/N)?'
ans1 = input(prompt1)
switch ans1
case {'Y', 'y'}
x = 5*5
case {'N', 'n'}
x = 5/5
otherwise
% the input was neither of the above
end

Community Treasure Hunt

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

Start Hunting!

Translated by