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

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

darova
darova le 5 Avr 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 commentaires
Ragini Ravichandren
Ragini Ravichandren le 5 Avr 2021
Modifié(e) : darova le 5 Avr 2021
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 le 5 Avr 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by