Search code examples
matlabfunctiondifferential-equations

User Made Matlab Function Fails Once All Variables are Cleared


I originally asked this question yesterday and found the answer myself; however, I used the clear all command in Matlab and now the function throws an error Undefined function or variable 'y'. I used the code from my answer function [s1] = L_Analytic3(eqn,t0,h,numstep,y0)

%Differential Equation solver for specific inputs
%   eqn is the differential equation
%   t0 is start of evaluation interval
%   h is stepize
%   numstep is the number of steps
%   y0 is the initial condition

syms y(x)
cond = y(0) == y0;
A = dsolve(eqn, cond);
s1 = A;
S1 = s1;
for x = t0 : h : h*(numstep)
    subs(x);
    if x == t0    
        S1 = subs(s1,x);
    else 
      S1 = [subs(S1), subs(s1,vpa(x))];
    end
end
end

and also put L_Analytic3(diff(y) == y,0,0.1,5,1) into the Command Window after entering clear all. I have to run a seperate code

syms y(x)
cond = y(0) == 1;
A = dsolve(diff(y) == y, cond);

before using my function in order for the function to work. Is this just because A,ans,cond,x, and y, are already defined by the 3 line code before using the function? If so, is there a way that I can use the function without having to use that 3 line code first?


Solution

  • When you do L_Analytic3(diff(y) == ...); you do not have variable y defined, so MATLAB complains - it has no way of knowing y is a symbol that will be defined in the function you are calling. You do not require all 3 lines of code. syms y(x) should be enough to define y and lets you use the function call you wanted.

    Now, there are 2 easy ways to fix this that I see:

    1. A script (or another function) that has syms y(x), followed by the call to L_Analytic3 the way you are doing it (which now does not need syms y(x), it has been defined already).
    2. Give anonymous equation as the input instead, say @(x) diff(x)==x, and change a line of L_Analytic3 slightly to A = dsolve(eqn(y), cond);

    Both ways work fine for this, no idea if 2nd one breaks in more complex cases. I would likely pick 1st version if you are doing symbolic stuff, and 2nd if you would like to have same function call to both numeric and symbolic functions.