Error using plot Vectors must be the same length.

2 views (last 30 days)
Error using plot
Vectors must be the same length.
Error in midpointfinal (line 33)
plot(t,y_m,'-o')
clc; clear all;
h=0.01;
Tmax = 2; % Maximum time
Tmin=1; %Minimum time
n = (Tmax-Tmin)/ h; % Maximum number of steps
%n=(t(2)-t(1))/h;
t = linspace(0,1,n+1);;
alpha=0.5;
mu=20;
%initials%
y_m(1)=2;
y_m(2)=exp(20.*h)+cos(h);
f_m(1)=20.*(y_m(1)-cos(t(1)))-sin(t(1));
f_m(2)=20.*(y_m(2)-cos(t(2)))-sin(t(2));
% Analytical solution of the differential equation
exact = @(t) exp(mu*t)+cos(t);
plot(t,exact(t));
hold
%Numerical solution
%f= @(t,y) mu*(y-cos(t))-sin(t); % Governing system of equations
%Midpoint Two step method%
for i=3:n
y_m(i)=y_m(i-2)+2.*h.*f_m(i-1);
f_m(i)=20.*(y_m(i)-cos(t(i)))-sin(t(i));
end
plot(t,exact(t))
hold
plot(t,y_m,'-o')
legend('Exact Solution','Leapfrog Solution','Location','NorthEast')
xlabel('t')
ylabel('y')
  2 Comments
Atsushi Ueno
Atsushi Ueno on 24 May 2022
Vector t and y_m must be the same length.
h = 0.01;
n = 100; % Maximum number of steps
t = linspace(0,1,n+1);
y_m(1)=2;
y_m(2)=exp(20.*h)+cos(h);
f_m(1)=20.*(y_m(1)-cos(t(1)))-sin(t(1));
f_m(2)=20.*(y_m(2)-cos(t(2)))-sin(t(2));
for i=3:n
y_m(i)=y_m(i-2)+2.*h.*f_m(i-1);
f_m(i)=20.*(y_m(i)-cos(t(i)))-sin(t(i));
end
size(t)
ans = 1×2
1 101
size(y_m)
ans = 1×2
1 100

Sign in to comment.

Accepted Answer

David Hill
David Hill on 24 May 2022
t = linspace(0,1,n);%vector t needs to be same length as y_m

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!