How do I create variable vectors with a new value for each iteration of a loop?

조회 수: 1 (최근 30일)
I wrote the following function, where t and y are supposed to give values for each iteration of the Euler method. However, I don't know how to properly allocate space for the values, nor ensure that the values change and are added to a 1Xn array for each iteration of the loop. Thanks!
function [t,y]=eulerMethod(f3, dt, Tf, t0, y0)
n=(Tf-t0)/dt;
nf=round(n,1);
y= zeros(1, nf);
yp = zeros(1, nf);
yn = zeros(1, nf);
tp= zeros(1, nf);
yp=y0;
tp(n+1,:);
for n=0:nf
tp(n+1)=t0+n*dt;
f3p(n+1)=f3(tp(n+1),yp(n+1));
yn(n+1)=yp(n+1)+dt*f3p(n+1);
yp(n+1) = yn(n+1);
end
t=tp;
y=yp;
end

채택된 답변

darova
darova 2021년 4월 5일
Here are some corrections
% yp=y0; % you are replacing variable yp with y0
yp(1) = y0; % you need to replace first value only
corrections2
tp= zeros(1, nf); % length of array nf
for n=1:nf-1 % start from '1' index
tp(n)=t0+n*dt; % you can access tp(n+1). It doesn't exist
f3p(n)=f3(tp(n),yp(n));
yp(n+1) = yp(n) + dt*f3p(n);
%yp(n+1) = yn(n+1); % you don't need yn variable at all
end
  댓글 수: 2
Ragini Ravichandren
Ragini Ravichandren 2021년 4월 5일
편집: darova 2021년 4월 5일
Hi!
Thanks so much! So, I ran the code as follows:
function [t,y]=eulerMethod(f3, dt, Tf, t0, y0)
n=(Tf-t0)/dt;
nf=round(n,1);
y= zeros(1, nf);
yp = zeros(1, nf);
tp= zeros(1, nf);
yp(1)=y0;
for n=1:nf
tp(n)=t0+n*dt;
f3p(n)=f3(tp(n),yp(n));
yp(n+1)=yp(n)+dt*f3p(n);
end
t=tp;
y=yp;
end
However, the final y value (2.310559058101177e4) is different from the one I got using the previous code: 2.198756668645101e+04, probably since the for loop starts at 1, rather than 0, and the loop is supposed to build on the inital tn value which should be t0+n*dt, where n=0. Is ther any way I could start the loop at 0 vs 1?
darova
darova 2021년 4월 5일
Increase size of tp
tp= zeros(1, nf+1); % length of array nf
for n=1:nf % till the end
Modify tp a bit
tp(n)=t0+(n-1)*dt; % you can access tp(n+1). It doesn't exist

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by