Save array values in a for loop

1 vue (au cours des 30 derniers jours)
omar rakgha
omar rakgha le 9 Avr 2022
Commenté : Jan le 9 Avr 2022
Hi!
I am trying to plot the error of a numerical ODE solver as the step size changes, but only the last value for error saves after the for loop (lines 22-23). How can I change this so it plots the error for each step change in i. Thank you in advance
clc;clear all;close all; format compact;
A = 2;Kc = 1;Ti = 0.1;
y1(1) = 0;
y2(1) = 2;
t(1) = 0;
syms x z1(x) z2(x);
ode1 = diff(z1,x)==z2(x);
ode2 = A*diff(z2,x)+Kc*z2(x)+Kc*z1(x)/Ti==0;
cond1 = z1(0)==0;
cond2 = z2(0)==2;
[z1(x),z2(x)] = dsolve([ode1,ode2],[cond1,cond2]);
for i = linspace(100,1000,10)
DeltaT = 50/i;
for n = 1:i
y2(n+1) = y2(n)-((1/A)*(Kc*y2(n)+Kc*y1(n)/Ti))*DeltaT;
y1(n+1) = y1(n)+y2(n)*DeltaT;
t(n+1) = t(n)+DeltaT;
end
vx = linspace(0,50,i+1);
error = max(abs(double(y1-z1(vx))))
end
plot(i,error,'x')
  1 commentaire
Jan
Jan le 9 Avr 2022
Some hints:
clear all removes all loaded functions from the memory. Reloading them from the slow disk wastes time and offers no advantage.
Avoid shadowingof important Matlab functions by variables. After "error=1" you cannot use the error() function anymore.

Connectez-vous pour commenter.

Réponse acceptée

Alan Stevens
Alan Stevens le 9 Avr 2022
Try replacing
error = max(abs(double(y1-z1(vx))))
with
error(i) = max(abs(double(y1-z1(vx))));
  1 commentaire
omar rakgha
omar rakgha le 9 Avr 2022
Thank u!!!!!!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by