Error plotting (Vector must be the same length)
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Davide Masiello
2022-4-13
编辑:Davide Masiello
2022-4-14
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 个评论
Davide Masiello
2022-4-13
编辑:Davide Masiello
2022-4-14
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!