Error plotting (Vector must be the same length)
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
clear all
clc
f=@(t,y) 4*y.^2;
F = @(t) 1/(4*(1-t));
a=0; b=0.95;
h=0.05;
n = (b-a)/h;
t = a:h:b;
y = zeros(1,length(t));
y(1) = 0.25;
%EULERS METHOD
for i = 2:n+1
y(i) = y(i-1) + h*f(t(i-1),y(i-1));
end
E=y;
fprintf(' Step number_i time_t Approximated solution Exact solution Relative Error\n')
for j = 1:n+1
m=abs(E(j)-F(t(j)));
n = abs(F(t(j)));
kE = m/n;
A(j) = F(t(j));
fprintf('%5d %18f %15f %20f %15f \n',j,t(j),E(j),F(t(j)),kE)
end
plot(t,A,'.-k', t, E, 'o-r')
xlabel('x');
ylabel('y(t)');
grid on
title('Part(a) Plot');
legend('Exact solution','Eulers solution')
**It all works for the table, but I'm getting an error for plotting. It says the vectors should be in the same length, but I don't get the problem.
Please help me.
Thank you.
0 comentarios
Respuestas (1)
Davide Masiello
el 13 de Abr. de 2022
Editada: Davide Masiello
el 14 de Abr. de 2022
The vector A has 19 elements, whereas t and E have 20.
clear all
clc
f=@(t,y) 4*y.^2;
F = @(t) 1/(4*(1-t));
a=0; b=0.95;
h=0.05;
n = (b-a)/h;
t = a:h:b;
y = zeros(1,length(t));
y(1) = 0.25;
%EULERS METHOD
for i = 2:n+1
y(i) = y(i-1) + h*f(t(i-1),y(i-1));
end
E=y;
fprintf(' Step number_i time_t Approximated solution Exact solution Relative Error\n')
for j = 1:n+1
m=abs(E(j)-F(t(j)));
n = abs(F(t(j)));
kE = m/n;
A(j) = F(t(j));
fprintf('%5d %18f %15f %20f %15f \n',j,t(j),E(j),F(t(j)),kE)
end
plot(t(1:end-1),A,'.-k', t(1:end-1), E(1:end-1), 'o-r')
xlabel('x');
ylabel('y(t)');
grid on
title('Part(a) Plot');
legend('Exact solution','Eulers solution')
2 comentarios
Davide Masiello
el 13 de Abr. de 2022
Editada: Davide Masiello
el 14 de Abr. de 2022
Yes
plot(t(1:end-1),A,'.-k', t(1:end-1), E(1:end-1), 'o-r')
I updated it in the answer too, so you can see the resulting plot.
Ver también
Categorías
Más información sobre 2-D and 3-D Plots 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!