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

1 回表示 (過去 30 日間)
Yasin Simsek
Yasin Simsek 2019 年 2 月 16 日
回答済み: Cris LaPierre 2019 年 2 月 16 日
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.

回答 (1 件)

Cris LaPierre
Cris LaPierre 2019 年 2 月 16 日
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.

カテゴリ

Help Center および File ExchangeSolver Outputs and Iterative Display についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by