MATLAB Answers

change variable value based on other variable in if loop

54 views (last 30 days)
avram alter
avram alter on 1 Jan 2020
Commented: avram alter on 1 Jan 2020
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.

Accepted Answer

Jim Riggs
Jim Riggs on 1 Jan 2020
Edited: Jim Riggs on 1 Jan 2020
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 Comments
avram alter
avram alter on 1 Jan 2020
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.

Sign in to comment.

More Answers (0)

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!