User input if, else if statement
10 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
OCDER
2017-11-2
编辑:OCDER
2017-11-2
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 个评论
OCDER
2017-11-3
编辑:OCDER
2017-11-3
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!