Search code examples
matlabloopsiterationcontinue

How to repeat for loop iteration in Matlab if an error occurred


I have this code in MATLAB:

for i = 1: n
   a = randi([0 500]);
   function (a);
end

When there is error during the execution of function(a) in iteration i=k the program stops. Is there any way to make the program repeat the same iteration (when there is an error) with a new value of a and continue the execution?


Solution

  • The solution to your problem is pretty simple. Just use try, catch.

    For loop that calls function

    for i=1:3
        a=randi([0 500]);
        try
            myfunction(a); %Statements that may throw an error
        catch
            %Code that is executed if myfunction throws error
        end
        disp(i) %Proves that the loop continuous if myfunction throws an error
    end
    

    Function

    function b = myfunction(a)
        b=a;
        error('Error!!!') %Function throws error every time it gets called
    end
    

    Output without try, catch

    Error using myfunction (line 3)
    Error!!!
    
    Error in For_Error (line 6)
        myfunction(a); %Statements that may throw an error
    

    Output with try, catch

    1
    
    2
    
    3