MATLAB Answers

How can strings be used in an if loop?

46 views (last 30 days)
Nathan Costin
Nathan Costin on 12 Jul 2016
Answered: Tom Hawkins on 14 Nov 2018
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

  0 Comments

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 12 Jul 2016
Edited: the cyclist on 12 Jul 2016
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 Comment

Sign in to comment.

More Answers (2)

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

  0 Comments

Sign in to comment.


Tom Hawkins
Tom Hawkins on 14 Nov 2018
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

  0 Comments

Sign in to comment.

Sign in to answer this question.