Am I passing a function through correctly?
Afficher commentaires plus anciens
I was trying to to write a function that uses the Euler method to calculate the nth iteration solution of a function y. As inputs, it takes a function handle passed through in terms of variables (t, y). Then it solves for the iteration number n, based on the desired final t value, Tf, t0, and the time step dt, using the equation tn=t0+n*dt =>Tf=t0+n*dt. Then outputs the vectors t and y of t and y values generated after each iteration so, starting with t0 and y0 and going up to the values (Tf, yn). I was wondering if the function would return every set of (t, y) vectors for each iteration in an array, if I allocated the space prior to the loop, or if I would need to simply print (tn, yn) at the end of the loop itself. I thought I would need to create an array in order to return every (t, y) vector created, instead of just the last one:
function [t,y]=eulerMethod(f3, dt, Tf, t0, y0)
syms n;
syms tn;
syms yn;
Tf=t0+n*dt;
S1=solve(Tf,n);
nf=round(S1);
yp=y0;
tp=t0;
nf=nf-1;
for n=0:nf
tn=t0+n*dt;
f3p=subs(f3,[t,y],[tn,yp]);
yn=yp+dt*f3p;
yp=yn;
end
syms t;
syms y;
t=tn;
y=yn;
return
Also, I was wondering if I passed the arbitrary function f3, correctly, as follows:
f3=@(t,y) %(write fct here);
eulerMethod(f3, dt, Tf, t0, y0)
Thanks!
3 commentaires
Jan
le 3 Avr 2021
This is very confusing. Why do you use symbolic expressions for such easy numerical tasks?
Tf = t0 + n * dt;
S1 = solve(Tf,n);
What about:
n = (Tf - t0) / dt; % Without symbolic maths
This is obscure although:
f3p=subs(f3,[t,y],[tn,yp]);
Are you sure that you do not want to use the numerical Euler method for a numerical integration? Then:
f3p = f3(t, y);
would be easier and clear.
Ragini Ravichandren
le 4 Avr 2021
Jan
le 4 Avr 2021
It is still unclear, why you want to use sym at all. The Euler method is a numerical method for an integration.
Your code looks confusing. Providing "Tf" and "t0", the symbolic calculation of the number of steps, renaming y0 to yp, yn to yp, yp to y is strange also. Finally it is still not clear to me, what this means: "Euler method to calculate the nth iteration solution of a function y." I do not know, what an "n.th iteration solution" is. Here the function is not "y" also.
Usually Euler methods looks like this:
function [t, y] = eulerMethod(fcn, t0, tf, dt, y0)
t = t0:dt:tf % Time steps
n = numel(t); % or: n = floor((tf - t0) / dt); % Number of steps
y = zeros(numel(y0), n); % Pre-allocate the output
y(:, 1) = y0; % Start at initial value
for k = 2:n
dy = fcn(t(k - 1), y(:, k - 1));
y(:, k) = y(:, k - 1) + dt * dy;
end
end
Réponses (0)
Catégories
En savoir plus sur Conversion Between Symbolic and Numeric dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!