Am I passing a function through correctly?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Jan
2021년 4월 4일
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
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Special Values에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!