MATLAB: Using functions: one from the script and another from the file.

functionsMATLAB

Hi, this is my first post and I am a new to matlab. I have a script which involves using two functions, sort of nested. I have one function in the main script and another in a seperate file which I use for the problem. This is just a sample of my problem and I believe if I can solve/understand this I will be able to tackle the main main. Below is a script and attached is a function.
clear
Np=5;
x1=linspace(-0.75,0.75,Np);
y1=linspace(-0.75,0.75,Np);
[ a , b , c] = fun1('f');
tspan=a;
Fx1 = b;
Fx2 = c;
[ ~ , d , e] = fun1('k');
x2 = d;
y2 = e;
fun =@(t1) f1(x1,y1,t1);
[t3,t4] = ode45(@(t1,y1) fun(t1),tspan ,0 );
% f1(1,1,1)
function y= f1(x1,y1,t)
x3 = d(x1,y1,t);
y3 = e(x1,y1,t);
y = x3.^2+y3.^2+sqrt(x3.^2+y3.^2);
end
Undefined function 'd' for input arguments of type 'double'.
Error in script>f1 (line 17)
x3 = d(x1,y1,t);
Error in script (line 13)
the code fails to recognize 'd' which it should because I have already defined it in fun1.m. Any help is appreciated.

Best Answer

The function written at the end of a script is not considered a nested function. The function f1 in your code is just a normal function, and the variables d and e are not visible in its scope. To make them visible inside the function to create a nested function by wrapping the code in your script in another function. For example
function y = myFun()
Np=5;
x1=linspace(-0.75,0.75,Np);
y1=linspace(-0.75,0.75,Np);
[ a , b , c] = fun1('f');
tspan=a;
Fx1 = b;
Fx2 = c;
[ ~ , d , e] = fun1('k');
x2 = d;
y2 = e;
fun =@(t1) f1(x1,y1,t1);
[t3,t4] = ode45(@(t1,y1) fun(t1),tspan ,0 );
% f1(1,1,1)
function y= f1(x1,y1,t) % now this is nested
x3 = d(x1,y1,t);
y3 = e(x1,y1,t);
y = x3.^2+y3.^2+sqrt(x3.^2+y3.^2);
end
end
Note: Now you will get another error, but that is not related to syntax. There is some mistake in the way you wrote the ODE.