It’s late – I can’t find where my error is in my error function. I’m attempting a parameter estimation.
function value = lv(t,y,p)
%Lotka-Volterra Model
%p(1)=a, p(2) = b, p(3) = c, p(4) = r.
value = [-p(1)*y(1)-p(2)*y(1)*y(2);-p(4)*y(2)+p(3)*y(1)*y(2)];
end
function error = lverr(p)
%LVERR: Function defining error function for
%example with Lotka-Volterra equations.
H = [30.0 47.2 70.2 77.4 36.3 20.6 18.1 21.4 22 25.4 27.1];
L = [4 6.1 9.8 35.2 59.4 41.7 19 13 8.3 9.1 7.4];
[t,y] = ode45(@lv,[0 10],[H(1);L(1)],[],p);
value = (y(:,1)-H').^2+(y(:,2)-L').^2;
%Primes transpose data vectors H and L
error = sum(value);
end
And the main filethat I use to execute the code:
clc;
clear all;
format long;
H = [30.0 47.2 70.2 77.4 36.3 20.6 18.1 21.4 22 25.4 27.1];
L = [4 6.1 9.8 35.2 59.4 41.7 19 13 8.3 9.1 7.4];
guess = [0.47;0.024;0.023;0.76];
[p,error] = fminsearch(@lverr,guess);
[t,y]=ode45(@lv,[0 10],[30.0; 4.0],[],p);
subplot(2,1,1)
plot(t,y(:,1))
subplot(2,1,2)
plot(t,y(:,2))
Here is the error:
??? Error using ==> minus
Matrix dimensions must agree.
Error in ==> lverr at 8
value = (y(:,1)-H').^2+(y(:,2)-L').^2;
The
ode45integrator is an adaptive step-size, variable-order Runge-Kutta method. What this means is that the step size used at each step depends on the behaviour of the solution at that point. What this implies is that the number of elements in the output[t,y]will vary greatly from run to run, and should never be relied upon.In
lverr(p), you want to take the difference between the result from such an integration, and some fixed-length vector. This will fail, practically always. You canode45to generate output only at specified times (adjust yourtspanto have as many elements asH)H(andL) in some physically meaningful sense.As an aside — please refrain from using
erroras a variable name; it’s a built-in function too, which can lead to confusion for both you and the Matlab interpreter.