Search code examples
matlabnestedenvironment-variablessymbolic-math

Matlab: "Error using assignin: Attempt to add "c" to a static workspace"


I have the following piece of function definition (test code):

function [X,Y,Z] = test(x,y,z)

syms a b c;
a = b + c;   % This is where it gets wrong

X=x;
Y=y;
Z=z;

keyboard

% nested functions
    function y = fun1(t,x)
        y=t+x;
    end

    function res = bvpbc(y0,yT)
       res= y0+yT;
    end

end

Basically, I have some nested functions within the test function, where I declared some symbolic variables a, b and c. However, when I run the function by typing

test(1,1,1)

there is always this error message:

Error using assignin
Attempt to add "b" to a static workspace.
 See MATLAB Programming, Restrictions on Assigning to
 Variables for details.

Error in syms (line 66)
        assignin('caller',x,sym(x));

Error in test (line 3)
    syms a b c;

It seems to be something wrong with the symbolic declarations, but I don't understand why. How can I fix it?

Thank you!

EDIT: In addition, whenever I remove the two nested functions, the test function will work just fine.


Solution

  • The following minimal working example recreates the problem, and as Andrew Janke explains in the comments, is not a bug:

    function foo
    syms A
    
        function nested
        end
    
    end
    

    you can work around it with an explicit assignment of the symbolic variable to the workspace:

    A = sym('A');