# How to use a variable from script in a function that is in another script

15 views (last 30 days)
Gabriel on 2 May 2024
Edited: Gabriel on 8 May 2024
Hello, I am coding a 2nd order differential solver and need to call a variable from the main script into a function script as shown below. I have tried using global however I have read that it is not accepted practice. Also note x2 and x3 are stored in another script called solver.m. Thank you!
Sam Chak on 2 May 2024
Based on the assumption that the 'solver.m' file solves a 2nd-order differential equation involving two state variables, x1 and x2, I noticed that you wanted to pass x2 and x3 to the function 'fx2x3()'. However, I'm curious about the origin of x3. It seems that 'dv3dt' represents another differential equation. Are you also looking to solve it alongside the other differential equation?
%% solver.m (Example)
odefun = @(t, x) [x(2); - x(1) - 2*x(2)]; % 2nd-order ODE
tspan = [0 10];
x0 = [1; 0];
[t, x] = ode45(odefun, tspan, x0);
plot(t, x), grid on, legend('x_{1}', 'x_{2}')
Stephen23 on 2 May 2024
"How to use a variable from script in a function that is in another script"

John D'Errico on 2 May 2024
Edited: John D'Errico on 2 May 2024
Just create your function like this. In my example, k3 and m3 will be assigned, so that you can see how it works.
k3 = 3;
m3 = 5;
fx2x3 = @(x2,x3) ((k3)/(m3))*(x2-x3);
The function handle fx2x3 uses the existing values of k3 and m3. We can evaluate it. And you can pass it into any function that will then use it. I'll again create a function handle.
fx2x3(1,2)
ans = -0.6000
There is no need to create an m-file to code something that simple. Were it more complex, then you could still use nested functions. Or, you can do as I do with the function complicatedMessOfCode.
fx2x3b = @(x2,x3) complicatedMessOfCode(x2,x3,k3,m3)
fx2x3b = function_handle with value:
@(x2,x3)complicatedMessOfCode(x2,x3,k3,m3)
As you can see, fx2x3b calls the messy function, passing in the existing values of k3 and m3. But now we can use it, again, anywhere we can pass it.
fx2x3b(1,2)
ans = -0.6000
Again, you can pass these functions into other tools that will then use them. They will be able to use the values of k3 and m3 as they are when the function handle was created.
function returnvalue = complicatedMessOfCode(x2,x3,k3,m3)
% Pretend something messy happen inside here, that requires multiple
% lines of code to evaluate. I'm too lazy to do more though.
returnvalue = ((k3)/(m3))*(x2-x3);
end
Steven Lord on 2 May 2024
This is one of the techniques described on this documentation page, which is linked to from the description of the odefun input argument on the documentation pages of most if not all of the ODE solvers, like ode45.