Error plotting (Vector must be the same length)
2 ビュー (過去 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!