Could someone please help me fix this code?

function dy=f(t,y)
L=2;
V1=10;
V2=5;
dydt= [-L/V1*y(1) -L/V2*(y(2)-y(1))];
end
%% preparations
a=0; b=10; N=100; % t0, t final, N values
h=(b-a)/N; % step size
t=linspace(a,b,N+1);
y0=[0.3 0]; % initial value(s)
m=length(y0); % size of ODE system
y=zeros(m,N+1); % numerical approx. vector
y(:,1)=y0;
L=2;
V1=10;
V2=5;
%% RK2 method algorithm
f=@(t,y) [-L/V1*y(1) -L/V2*(y(2)-y(1))];
for j=1:N
k1=f(t(j),y(:,j));
k2=f(t(j)+0.5*h,y(:,j)+0.5*h*k1);
y(:,j+1)=y(:,j)+h*k2;
end
plot(t, y(1,:), t,y(2,:), 'g')
hold on
exact1=0.3*exp(-0.2*t);
exact2=0.6*(exp(-0.2*t)-exp(-0.4*t));
Plot (exact 1, y(1, :), exact2, y(2,:))
hold off
axis square
grid
And this is the message I get: "Unable to perform assignment because the size of the left side is 2-by-1 and the size of the right side is 2-by-2."
I would really appreciate your help.
D.

 Accepted Answer

function main
%% preparations
a=0; b=10; N=100; % t0, t final, N values
h=(b-a)/N; % step size
t=linspace(a,b,N+1);
y0=[0.3 0]; % initial value(s)
m=length(y0); % size of ODE system
y=zeros(N+1,m); % numerical approx. vector
y(1,:)=y0;
L=2;
V1=10;
V2=5;
%% RK2 method algorithm
f=@(t,y) [-L/V1*y(1) -L/V2*(y(2)-y(1))];
for j=1:N
k1=f(t(j),y(j,:));
k2=f(t(j)+0.5*h,y(j,:)+0.5*h*k1);
y(j+1,:)=y(j,:)+h*k2;
end
exact1=0.3*exp(-0.2*t);
exact2=0.6*(exp(-0.2*t)-exp(-0.4*t));
plot (t, exact1, t, y(:, 1), t, exact2, t, y(:,2))
hold off
axis square
grid
end

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!