How can i use a vector variable inside a function normally

4 views (last 30 days)
I have this code i'm trying to get to run
% This is a driver program which calls different methods at same place
clc
format long
syms t y;
tspan = 2:0.25:3; % t-values = startpoint:h:endpoint
y2 = 2; % initial condition
functiona=@(t,y) -y+t*y^(1/2);%put f(t,y) here
df=@(t,y) y-(3/2)*t*y^(1/2)+y^(1/2)+(1/2)*t^2;%put f'(t,y) here
ddf=@(t,y) -y+(7/4)*t*y^(1/2)-2*y^(1/2)-(3/4)*t^2+(3/2)*t;%put f''(t,y) here
dddf=@(t,y) y+(11/4)*t*y^(1/2)+(13/4)*y^(1/2)+(7/8)*t^2-(5/2)*t+3/2;%put f'''(t,y) here
[t_values,y_values]=ode45(functiona,tspan,y2);
[t_values,w_values]=taylor_4th(functiona,df,ddf,dddf,tspan,y2);
syms y(t)
% This is the exact solution
f = @(tspan) (tspan-2+2^(1/2)*exp(1)*exp((-1/2)*tspan))^2;%put exact solution here;
error1 = abs(f(tspan)'-y_values);
error2 = abs(f(tspan)'-w_values);
varnames = {'t_values','ODE45', 'Taylor','exact_values', 'Errorode45','Error-Taylor'};
table(t_values, y_values,w_values, f(tspan)',error1,error2,'VariableNames',varnames)
the problem appears to be with the line 18
f = @(tspan) (tspan-2+2^(1/2)*exp(1)*exp((-1/2)*tspan))^2;%put exact solution here;
I think it has to do with needing to put periods in since 'tspan' is a vector and the operations need to be put in componentwise.

Answers (2)

Voss
Voss on 28 Jan 2022
Looks like your hunch was correct: there was a missing period in that expression.
% This is a driver program which calls different methods at same place
clc
format long
syms t y;
tspan = 2:0.25:3; % t-values = startpoint:h:endpoint
y2 = 2; % initial condition
functiona=@(t,y) -y+t*y^(1/2);%put f(t,y) here
df=@(t,y) y-(3/2)*t*y^(1/2)+y^(1/2)+(1/2)*t^2;%put f'(t,y) here
ddf=@(t,y) -y+(7/4)*t*y^(1/2)-2*y^(1/2)-(3/4)*t^2+(3/2)*t;%put f''(t,y) here
dddf=@(t,y) y+(11/4)*t*y^(1/2)+(13/4)*y^(1/2)+(7/8)*t^2-(5/2)*t+3/2;%put f'''(t,y) here
[t_values,y_values]=ode45(functiona,tspan,y2);
% [t_values,w_values]=taylor_4th(functiona,df,ddf,dddf,tspan,y2);
syms y(t)
% This is the exact solution
% f = @(tspan) (tspan-2+2^(1/2)*exp(1)*exp((-1/2)*tspan))^2;%put exact solution here;
f = @(tspan) (tspan-2+2^(1/2)*exp(1)*exp((-1/2)*tspan)).^2;%put exact solution here;
error1 = abs(f(tspan)'-y_values);
% error2 = abs(f(tspan)'-w_values);
disp(error1);
1.0e-09 * 0.000000888178420 0.175975678473606 0.029717561744746 0.082043261073750 0.046412207410640

Matthew Allred
Matthew Allred on 29 Jan 2022
I was able to find the corrected code
f = @(tspan) (tspan-2+2.^(1/2).*exp(1).*exp(-tspan.*(1/2))).^2
It appears i just needed to put a period before every multiplication, division, exponential etc operator.
  1 Comment
Voss
Voss on 29 Jan 2022
That's fine, but actually only the last period (.^) is necessary because all the other operations are between a vector and a scalar.

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!