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

조회 수: 1 (최근 30일)
Haley Kelly
Haley Kelly . 2021년 11월 17일
댓글: Jon . 2021년 11월 17일
Hello,
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
Stephen23
Stephen23 2021년 11월 17일
@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:
STRNCMPI(view_data,'yes',numel(view_data))
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Yongjian Feng
Yongjian Feng 2021년 11월 17일
yes is a string
if strcmpi(view_data, 'yes')
  댓글 수: 3
Haley Kelly
Haley Kelly 2021년 11월 17일
@Yongjian Feng @Stephen thank you both so much... disp worked perfectly! I feel so dumb haha... thank you again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jon
Jon 2021년 11월 17일
편집: Jon 님. 2021년 11월 17일
put single or double quotes around yes
if view_data == 'yes'
and also around no in the following line
  댓글 수: 6
Jon
Jon 2021년 11월 17일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by