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
编辑: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