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!