User input if, else if statement
조회 수: 24 (최근 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에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!