MATLAB: How to read this code

codeode45

Suppose I run this code by typing in the command line [t p] = ode45(@spring,[0 4], [0 0]); I don't understand first of all how MATLAB knows p is a vector and how does MATLAB know p is a 2×1 matrix … ( It has to be a 2×1 matrix because I have 2 expressions in order to solve the system of differential equations). I think the answer comes from the initial values [0 0] but the initial value is not p!! p is unknown how come pdot is created…?
function pdot = spring(t,p,c,w)
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = sin(t) -c*p(2) - (w^2)*p(1);

Best Answer

MATLAB doesn’t know that pdot is a (2x1) column vector until you tell it. That’s what you’re doing when you preallocate it with the zeros statement. Usually, you declare the value of p by preallocating it as ‘pdot = zeros(2,1);’, but since your initial conditions vector is [0 0], it preallocates correctly. The initial conditions vector is the first value for p because you just defined it as the initial condition (starting values) for p.
Related Question