fminbnd gives "Operands to the || and && operators must be convertible to logical scalar values"

1 view (last 30 days)
I am trying to write value function iteration method. I write following function;
function val = valfnc(k)
global beta alpha kspace kmax kmin grid v0 k0 index
index = find(abs(k-kspace) <= (kmax-kmin)/(2*grid));
val = log((k0^alpha) - k) + beta*v0(1,index);
val = -val;
end
The main code is
%initializations
clear all;
clc;
global alpha beta delta kmin kmax grid kspace k0 v0
alpha = 0.3;
beta = 0.95;
delta = 0.1;
kmin = 0;
kmax = 1;
grid = 1000;
kspace = kmin:(kmax-kmin)/grid:kmax;
[N,n] = size(kspace);
v0 = zeros(1,n);
v1 = zeros(1,n);
iteration = 1;
V = zeros(iteration, n);
policy = zeros(iteration, n);
fun = @valfnc;
while iteration < 11
for i = 1:n
k0 = kspace(1,i);
kprime = fminbnd(fun,kmin,kmax);
policy(iteration, i) = kprime;
v1(1,i) = -valfnc(kprime);
V(iteration, i) = v1(1,i);
end
v0 = v1;
iteration = iteration + 1;
end
Somehow I get the error message Operands to the || and && operators must be convertible to logical scalar values. Error in fminbnd (line 346) if ( (fu <= fw) || (w == xf)) Error in Hw1 (line 35) kprime = fminbnd(fun,kmin,kmax);
I have no idea about why this happens. I will be grateful for any comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 16 Feb 2019
Your objective function must return a scalar value. It appears to not always be doing that. When iteration=1 and i=42, it returns a complex number:
>> fun(.5)
ans =
2.1504 - 3.1416i
If I modify valfcn so that val = -abs(val), I no longer get the error.
Whether that is the correct approach or not is up to you.

Community Treasure Hunt

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

Start Hunting!