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
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!