change variable value based on other variable in if loop

조회 수: 17 (최근 30일)
avram alter
avram alter 2020년 1월 1일
댓글: avram alter 2020년 1월 1일
I have a simple code that takes a user's input, and then changes 2 variables based on that:
var1 = 0;
var2 = 0;
in1 = input('first: ', 's');
in2 = input('second: ', 's');
if in1 = 3 && in2 = 4;
var1 = 2;
var2 = 5;
elseif in1 = 6 && in2 = 7;
var1 = 8;
var2 = 9;
else
disp('invalid input');
end
I didn't really expect it to work, as I was sure I had the syntax wrong. I get the error:
The expression to the left of the equals sign is not a valid target for an assignment.
and I am wondering how I can fix the syntax.

채택된 답변

Jim Riggs
Jim Riggs 2020년 1월 1일
편집: Jim Riggs 2020년 1월 1일
Your input command is requesting a string input:
in1 = input('first: ','s');
in2 = input('second: ','s');
This results in in1 and in2 being strings.
To input them as numbers, simply omit the 's'
in1 = input('first: ');
in2 = input('second: ')'
Also, to perform logical comparrison, use 2 equal signs, e.g.:
if in1 == 3 && in2 == 4
  댓글 수: 5
Stephen23
Stephen23 2020년 1월 1일
편집: Stephen23 2020년 1월 1일
Nesting input inside str2double is more robust because input by default will execute any input code the user enters. So your user can (maliciously or accidentally) run any code they want, using that input command. With the 's' option input does NOT execute their arbitrary code, but instead returns a character vector, literally what they entered. str2double will convert this character vector to a number if possible, otherwise it returns NaN...
Thus a more robust solution is to nest input inside str2double:
in1 = str2double(input('first: ','s'));
This guarantees that in1 is either a valid number or NaN, without any arbitrary code being evaluated. If you want the user to enter more complex data, e.g. a vector of numbers, then this requires a bit more processing, e.g.:
Of course the best solution is to ditch input entirely and just write functions/classes with well-checked input arguments...
avram alter
avram alter 2020년 1월 1일
This was more of a very basic version of a code I am writing. I'm going to do away with input entirely, and rely on serial data received from some equipment. I don't currently have that hardware on me, Soni make do with just inputs as a foundation. Thanks for the answer, very thorough and extremely helpful.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by