MATLAB: How to resolve “Error using assignin: Attempt to add ”c“ to a static workspace”

anonymousassigninerrorfunctionnestedstaticsymSymbolic Math Toolboxsymsworkspace

I get the following error when I try to run my script:
>> n = 4; zeich = 1; tZme = Zmatrixeig4(n,zeich);
Timings for ode15s (Frank U)
Error using assignin
Attempt to add "ts" to a static workspace.
See Variables in Nested and Anonymous Functions.
The script is as follows:
function [tZme, ys] = Zmatrixeig4(n,zeich)
if nargin == 0 % n = size of square A(t) matrix, zeich = 1 means plot, else no plots
n = 3; zeich = 0;
end
if nargin == 1 % default: no plot, even for n = 2 and 3
zeich = 0;
end
% try eta = 5000, 5000000 and see the errors decrease to 10^-8, 10^-12 averages
eta = 5000; tf = 5; options = odeset('reltol',10^-13); % adjust to taste !
fprintf('\n Timings for ode15s (Frank U)\n')
% starting to solve the eigenproblems A(t) x(t) - lambda(t) x(t) = 0
function [f,g] = derive(n) % I made this symbolic part into its own function ….
syms ts
% A 5 by 5 or smaller example with actual dimensions determined by the input n
Ats = [sin(ts),exp(sin(ts)),10-3*ts+4*ts^2+sin(ts),0,ts;
exp(sin(ts)),cos(ts),(2+ts^2-ts^4)/(1+ts),sin(ts^2-1)*cos(2*ts),(ts^2+1)/(2*ts+1);
10-3*ts+4*ts^2+sin(ts),(2+ts^2-ts^4)/(1+ts),(1-cos(ts))/(3+sin(ts))^2,17*ts-ts^2,exp(ts);
0,sin(ts^2-1)*cos(2*ts),17*ts-ts^2,sin(exp(ts)),exp(cos(7*ts));
ts,(ts^2+1)/(2*ts+1),exp(ts),exp(cos(7*ts)),-ts^3];
% enter given function A(t) here
fprintf(' \n ')
Ats = Ats(1:n,1:n) % function A(ts) symbolic output, a matrix of size n by n
dAts = diff(Ats) % derivative function dA(ts) symbolic output
f = matlabFunction(Ats); % f and g to be called
g = matlabFunction(dAts); % by main program
end
[f,g] = derive(n) % and now I try to call it up to work with f(t) and g(t) in the sequel ….
tic
A0 = f(0); n = length(A0),
[V,D] = eig(A0); lam = diag(D)';
Y = [V;lam]; Y = Y(:); % QR computed eigendata for t = 0 as starting values
Ax = zeros(n^2+n,n^2+n); b = zeros(n^2+n,1); % for use in ode15s
function dx = odefun_Zeig(t,Y)
for j = 1:n
k = j*n+j-n:j*n+j; xj = Y(j*n+j-n:j*n+j-1);
Ax(k,k) = [f(t)-Y(j*n+j)*eye(n),-xj; 2*xj',0];
b(k) = [(-eta*(f(t)-Y(j*n+j)*eye(n))-g(t))*xj;-eta*(xj'*xj-1)];
end
dx = Ax\b;
end
[tZme,y] = ode15s(@odefun_Zeig,[0,tf],Y,options);

Best Answer

So the reason you ran into the "Error using assignin. Attempt to add "ts" to a static workspace." was because of a quirky result of how the symbolic concepts are implemented as a toolbox, and not in the MATLAB syntax itself.
While syms ts may look like a static variable declaration, it isn't. It's just a regular function call. It's using MATLAB's "command" invocation style to look like syntax, but it's really equivalent to syms('a', 'b', 'c'). And nested functions make the workspace static, so you can't dynamically add variables, which the syms function does in its implementation using assignin.
So all you have to do is change your declaration of 'syms ts' to:
ts = sym('ts');