How to stop a script if conditions are met.
1,819 ビュー (過去 30 日間)
古いコメントを表示
I am using the 'if' function to detect if a user inputs a number that is not 5 digits long. What I would like is a function that stops the script if a certain condition is met without displaying an error message.
P.S. I'm very new to MATLAB.
1 件のコメント
Jingyang Xie
2021 年 1 月 6 日
Hi Cory, have you solved this problem? I think I encountered the same problem...
採用された回答
Walter Roberson
2012 年 2 月 2 日
編集済み: MathWorks Support Team
2018 年 11 月 9 日
9 件のコメント
Muhammad Usman Saleem
2022 年 11 月 5 日
Respected Sir @Walter Roberson, I not get the point your shared. Will you please amend this suggestion in my code shared above please?
Walter Roberson
2022 年 11 月 5 日
notdone = true(9,1);
while any(notdone)
if rcp(i,m)<0.1 & trcp(i,m) > 0.8
ECP{i,m}=Ecp{i,m};
notdone(1) = false;
end
if recp(i,m)<0.1 & trecp(i,m) > 0.8
ECN{i,m}= Ecn{i,m};
notdone(2)=false;
end
%etc
end
その他の回答 (2 件)
Hamid Ramezani
2019 年 9 月 30 日
you may use "error" function instead of return
3 件のコメント
Adam K
2020 年 12 月 10 日
編集済み: Adam K
2020 年 12 月 10 日
I think a 'msgbox' to really alert the user what is the issue, and then the 'error' funcition to stop the code would be a workaround. This way the user is aware that the issue is not really an 'error' when they see the red error font.
msg = "You've got a number that is not 5 digits long";
f = msgbox(msg)
error(msg)
Rik
2020 年 12 月 10 日
I wonder if it is possible to detect if the code is running in a try block. In such cases the message might be more confusing than simply throwing the error.
Korosh Agha Mohammad Ghasemi
2024 年 6 月 25 日
移動済み: Voss
2024 年 6 月 25 日
To stop a script in MATLAB without displaying an error message when a user inputs a number that is not 5 digits long, you can use the return function. The return function will exit the function or script without an error message. Here is an example:
% Request user input
userInput = input('Please enter a 5-digit number: ', 's');
% Check if the input is 5 digits long
if length(userInput) ~= 5
fprintf('Input must be a 5-digit number. Exiting script.\n');
return;
end
% Continue with the rest of your script
disp('Input is valid. Continuing script...');
% ... rest of your script
Explanation:
- Request User Input: Use input to get the user input as a string.
- Check the Length: Use length to check if the input length is not equal to 5.
- Return Function: Use return to exit the script if the condition is met, and display a message using fprintf.
This will ensure that the script stops if the user input is not a 5-digit number, and it will do so without throwing an error.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!