Am I passing a function through correctly?

1 Ansicht (letzte 30 Tage)
Ragini Ravichandren
Ragini Ravichandren am 3 Apr. 2021
Kommentiert: Jan am 4 Apr. 2021
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 Kommentare
Ragini Ravichandren
Ragini Ravichandren am 4 Apr. 2021
Got it. I was wondering whether I had originally had the following function:
function [t,y]=eulerMethod(f3, dt, Tf, t0, y0)
syms n;
n=(Tf-t0)/dt;
nf=round(n,1);
yp=y0;
for n=0:nf
tp=t0+n*dt;
f3p=f3(tp,yp);
yn=yp+dt*f3p;
yp=yn;
end
t=tn;
y=yp;
However, I couldn't really get t and y to return as outputs at the end after getting through the loop and setting them equal to yp, and tn.
Jan
Jan am 4 Apr. 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

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by