Supplied objective function must return a scalar value in fminunc

2 views (last 30 days)
I write the following code for AR(2) process maximum likelihood estimation
global y t;
y = [1 2 4 6 4 12 11 13 11 14 16 17]';
T = length(y);
t = [1:T]';
x0 = [1, 1, 0.1, 0.1];
[x, loglval] = fminunc(@(x) logl(x(1), x(2), x(3), x(4)), x0);
disp(x)
and the log likelihood function
function val = logl(a, b, p, s)
global y t T
f = y(2:T) - a*ones(T-1,1) - b*t(2:T) - p*y(1:T-1) - p*a*ones(T-1,1) - p*b*t(1:T-1);
val = -log(2*pi)*T/2 - T*log(s)/2 + log((1-p^2)^(1/2)) - (1/(2*s))*((1-p^2)*(y(1)-a-b*t(1))^2 + sum(f.*f));
end
But I get Supplied objective function must return a scalar value error. ı do not understand the error. I run the code with isscalar(val) and it returns 1. Could you help me?

Accepted Answer

Walter Roberson
Walter Roberson on 6 Jun 2019
%driving script
global y t;
%your function
global y t T
Since you do not initialize T within your function or within the context of a global, the value of it will be empty by default, giving you an empty result.
We recommend firmly against using global, as these kinds of mistakes are too easy to make with global.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!