Save array values in a for loop

1 visualización (últimos 30 días)
omar rakgha
omar rakgha el 9 de Abr. de 2022
Comentada: Jan el 9 de Abr. de 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 comentario
Jan
Jan el 9 de Abr. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Alan Stevens
Alan Stevens el 9 de Abr. de 2022
Try replacing
error = max(abs(double(y1-z1(vx))))
with
error(i) = max(abs(double(y1-z1(vx))));

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by