Using a string in an if statement to print data from excel.

5 views (last 30 days)
I am trying to get data from an excel sheet to print from user in put (yes/no) this is what i have if anyone has any suggestions please let me know thank you!
  1 Comment
Stephen23 on 17 Nov 2021
@Haley Kelly: a much more robust approach is to use STRCMPI, just as Yongjian Feng showed.
Unlike the approach you are trying to use with ==, STRCMPI will work for different input types (so makes your code more robust) as well as handling different character cases (so it does not matter if your user enters "YES" or "yes").
You could even do this:
which would allow your user to enter any of "Y", "y", "YES", or "yes".
The approach you are trying to use is fragile and does not offer that flexibility.

Sign in to comment.

Accepted Answer

Yongjian Feng
Yongjian Feng on 17 Nov 2021
yes is a string
if strcmpi(view_data, 'yes')
Haley Kelly
Haley Kelly on 17 Nov 2021
@Yongjian Feng @Stephen thank you both so much... disp worked perfectly! I feel so dumb haha... thank you again!

Sign in to comment.

More Answers (1)

Jon on 17 Nov 2021
Edited: Jon on 17 Nov 2021
put single or double quotes around yes
if view_data == 'yes'
and also around no in the following line
Jon on 17 Nov 2021
Yongjian's use of strcmpi is much better. The expression view_data == 'yes' actually yields a 1 x 3 logical array which in the case that view_data really is assigned to the string 'yes' will be given by [1 1 1] (true true true) .
The if statement will handle this ok, and only pass if all the elements of the logical vector are true, but it is nicer to actually do a string comparison using strcmpi, this will also guard against problems with case sensitivity. Note that if the user had responded with the string 'Yes' instead of 'yes', then view_data=='yes' would equal [0 1 1] and the if statement would consider the expression to be false.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!