0

I tried writing an Ordinary Differential Equation in MATLAB.

I wrote this code:

function [y] = odefun(t,y)
t = [0:0.01:10];
y = [0 0]';
y(1) = y(2);
y(2) = sin(2*t)-2*y(2)-2*y(1);  % I get an error here
end

I get an error in the last line in this code. MATLAB doesn't show me what the error is. It just tells me I have an error in that line.

Why do I get this error and how to resolve it?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
james
  • 23
  • 7

2 Answers2

0

You try to assign to y(2) a vector of 1001 elements:

>> size(sin(2*t)-2*y(2)-2*y(1))

ans =

           1        1001

The error message is pretty clear:

In an assignment A(:) = B, the number of elements in A and B must be the same.

Also, y and t are never use since you redefined them in the function.

TwistedSim
  • 1,960
  • 9
  • 23
0

What you want is to carefully read the documentation of the diverse ode solvers and the examples there and then correct your code to something like

% Solve ODE y''(t)+2*y'(t)+2*y(t) = sin(2*t), y(0)=y'(0)=0
function ydot = odefun(t,y)
  ydot = zeros_like(y)
  ydot(1) = y(2);
  ydot(2) = sin(2*t)-2*y(2)-2*y(1);
end
% or 
% odefun = @(y,t) [ y(2); sin(2*t)-2*y(2)-2*y(1) ]

% define sample points
tspan = [0:0.01:10];
% define initial value to t=tspan(1)
y0 = [0 0]';
[ t, y ] = ode45(odefunc, tspan, y0)
% t,y now contain the times and values that 
% the solution was actually computed for.
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51