# How to use substitution on function handle?

3 views (last 30 days)
I-Chun on 23 Nov 2023
Edited: I-Chun on 23 Nov 2023
I use an example to simplify my problem. Some steps are as follows:
(1) There is a system of linear equations such as
Use analytical method to solve and.
(2) And a differential equation is
Substitute and solved from step(1) into the differential equation, then use numerical method to solve with .
(3) Another differential equation is
Replace A with solved from step(2), then use numerical method to solve with .
is numerically solved, so I use spline which will give a function handle form. Because my differential equation is actually very complicated, it’s not as simple as just multiplying by 6, so I must use substitution here. However, "subs" can only be used for symbolic or double form, are there other ways to use substitution on function handle? Thank you for any suggestions.
clear
clc
% Step 1
syms z x y;
A = [5 2; 1 1];
B = [12*z; 3*z];
Sol = A\B;
xz = matlabFunction(Sol(1));
yz = matlabFunction(Sol(2));
% Step 2
syms a;
ode_a = @(z, a) xz(z)*yz(z)*a;
initial_a = 1;
[z_a, values_a] = ode45(@(z, a) ode_a(z, a), [0, 1], initial_a);
a_sol = @(z) interp1(z_a, values_a, z, 'spline'); % Here a_sol is a function handle.
% Step 3
syms A
ode_b = @(z, b) 6*A;
ode = subs(ode_b, A, a_sol(z)); % This step mistakes, "subs" can not be used for function handle.
initial_b = 0;
[z_b, b_values] = ode45(@(z, b) ode(z, b), [0, 1], initial_b);

John D'Errico on 23 Nov 2023
Edited: John D'Errico on 23 Nov 2023
ODE45 CANNOT use symbolic parameters. PERIOD. No matter how you try to trick things, you cannot pass a symbolic parameter (here A) into ODE45. For that matter, neither can you do that with INTERP1.
INTERP1 and ODE45 are purely numerical tools.
If you know the value of that parameter, then yes, you can do what you ask. But then it becomes a purely numerical problem.
I-Chun on 23 Nov 2023
Edited: I-Chun on 23 Nov 2023
Thank you. But if I don't use "subs", the code can run even though I use spline:
% Step 3
syms A
ode_b = @(z, b) 6*a_sol(z);
%ode = subs(ode_b, A, a_sol);
initial_b = 0;
[z_b, b_values] = ode45(@(z, b) ode_b(z, b), [0, 1], initial_b);
ode45 can indeed solve INTERP1 functions