Clear Filters
Clear Filters

User input if, else if statement

9 views (last 30 days)
Debbie Oomen
Debbie Oomen on 2 Nov 2017
Edited: OCDER on 3 Nov 2017
I want my script to ask the user if he/she wants more information on the script. When the user selects yes, then matlab should open a txt file in the editor with more information. If the user selects no, then matlab should continue running the script beneath it. I have the following script:
info=menu('More information?', 'Yes', 'No');
if info = 1
open Results1.txt;
end
if info = 2
fprintf('script will run')
continue
end
However, I keep on getting this error: The expression to the left of the equals sign is not a valid target for an assignment.
How can I make sure this does not happen?

Accepted Answer

OCDER
OCDER on 2 Nov 2017
Edited: OCDER on 2 Nov 2017
You need a "==" instead of "=" for comparing values. Here are some other comments:
info = menu('More information?', 'Yes', 'No');
if info == 1
open Results1.txt;
pause; %probably should put a break / pause / return here to prevent script from running.
elseif info == 2
fprintf('script will run\n'); %added \n to ensure next print statement is on next line.
%continue; %is this inside a for/while loop? Then continue works. Otherwise, continue not needed.
end
  2 Comments
Debbie Oomen
Debbie Oomen on 2 Nov 2017
Worked like a charm! I have a follow-up question: when I choose either yes or no on the menu and even when I try to close it, my script just keeps running. Do you maybe have any idea why?
OCDER
OCDER on 3 Nov 2017
Edited: OCDER on 3 Nov 2017
Hi Debbie,
your script keeps running because you don't have a command to end the script. Try this: instead of using scripts, turn it into a function - it's generally good to use functions as each "script" now becomes contained and can be used in bigger projects. All you need to do is add the function name in the first line that matches your script name. Then use return to end the function when you want it to. EX: assuming your file name is runScript.m , try this :
function runScript()
info = menu('More information?', 'Yes', 'No');
if info == 1
open Results1.txt;
return; %end the function early to prevent running script
elseif info == 2
fprintf('script will run\n');
else
fprintf('canceled\n');
return;
end
%Here should be the rest of your script...
disp('Script has run'); %This message will show only if user chooses
%"No" and script has run.

Sign in to comment.

More Answers (0)

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!