How to run the function again after a error?

조회 수: 4 (최근 30일)
Ibrahim A
Ibrahim A 2021년 5월 16일
답변: Aditya Patil 2021년 5월 19일
I am having a function where I input a time limit (T_limit) and in the body of the program some independent time(T_7) calculated. I am writing comparing these 2 time varibales, if the T_limit>T_7, function executes normally, but if the T_7 > T_limit, error message thrown and ask user to input a new time(T_limit) and executes the function again with this value. My problem is that, my code stuct in a infinite loop. Is there a way to execute function again with this new variable(T_limit)?
function [motion] = motionPlanning(j_max,a_max,v_max,length,T_limit)
%...
%%% FC2 - Time Violation
if (T7<T_limit) || (T_limit == 0)
disp("### MP - FC2 + Time is not violated (DSP) ###" );
motion.mp_feasibility{1,1} = ["Time Violation ", true];
else
motion.mp_feasibility{1,1} = ["Time Violation ", false];
try
error("### MP - FC2 + Time has been violated (DSP) ###");
catch
disp("### MP - FC2 + Enter new time limit (DSP) ###");
fprintf("New time limit: %d", T_limit);
[motion] = motionPlanning(2,0,0,200,T_limit);
end
end
  댓글 수: 2
Star Strider
Star Strider 2021년 5월 16일
The problem is that the ‘motionPlanning’ function is calling itself internally. (This is termed ‘recursion’ and is to be avoided.)
Also, the ‘T7’ variable and appraently several others, are not being passed to it. (I have no idea what the structure of the rest of the code is, so if this function is inside another function, it would automatically inherit ‘T7’ from the outer function workspace.)
Ibrahim A
Ibrahim A 2021년 5월 16일
편집: Ibrahim A 2021년 5월 16일
This is the main function not in another function. So if i make another function and call motionPlanning inside this function. Would that eliminate recursion?

댓글을 달려면 로그인하십시오.

채택된 답변

Aditya Patil
Aditya Patil 2021년 5월 19일
I would recommend separating the logic of the function and the code to take inputs from the user. Two of the possible ways to do this are,
  1. The function can verify the input and throw error if they are invalid. An outer while loop asks for input from the user, calls the functions, and repeats if the function throws an error. Else, the while loop exists.
  2. The outer loop verifies the inputs and calls the function only if the inputs are valid. Else, it asks for the inputs from user again.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Systems of Nonlinear Equations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by