Search code examples
matlabcompiler-errorspersistent

The PERSISTENT declaration must precede any use of the variable


While working on my matlab homework, I came across a very strange bug. Here's my code:

function [z,times] = Divide(x,y)

    persistent times;

    if (y == 0)
        if (isempty(times))
            times = 1;
        else
            times = times + 1;
        end
    end

    z = x/y;
end

When run, this gives me the error:

Error: File: Divide.m Line: 3 Column: 16
The PERSISTENT declaration must precede any use of the variable times.

This is strange, because it is telling me that I need to declare the variable as persistent before I declare it as persistent (!?). I have no idea what I'm doing wrong here, so if there's some strange workaround that I should be using, please tell me.


Solution

  • The error message means : you've used the 'times' before you declare it as persistent variable. As you used 'times' in return variables.

    One of the solution might be keep two different variables for 'times', one for persistent, and another one for return variable.

    Paste my change here for your reference. Good luck!

    function [z,times] = Divide(x,y)
        persistent p_times;
    
        if (y == 0)
            if (isempty(p_times))
                p_times = 1;
            else
                p_times = p_times + 1;
            end
        end
    
        times = p_times;
        z = x/y;
    end