How do I create variable vectors with a new value for each iteration of a loop?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Ragini Ravichandren
el 5 de Abr. de 2021
Comentada: darova
el 5 de Abr. de 2021
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 comentarios
Respuesta aceptada
darova
el 5 de Abr. de 2021
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 comentarios
Ragini Ravichandren
el 5 de Abr. de 2021
Editada: darova
el 5 de Abr. de 2021
darova
el 5 de Abr. de 2021
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!