I want to maximize this function using fminbnd
in MATLAB.
I am not able to correctly define the function in MATLAB. How can I create a loop for i
to define the function accordingly and finally apply fminbnd
?. Here's my code ( which is actually wrong ):
k = 0.1;
L = sum(k - (i/n)) + sum(((i/n) - k)*log(k - (i/n))) + k;
fminbnd(-L, [], []);
Any help will be very appreciated.
There are two things concerning your problem.
First : the thing with the loop
MATLAB is great at vectorizing stuff. The command sum
adds-up a vector, so you need to create the vector i = 1:n
(from 1
to n
... spaced by 1) yourself:
n = 10; % maximum in sum
i = 1:n; % line-space => use MATLAB's vetorization
in = i/n; % put this in a new variable for the sake of conciseness
k = 10; % some random value
L = sum( (k - in) + (in - k).*log(k - in) + k )
the output is:
L = -17.7921
Second: the thing with optimizing a function
Handing over functions in MATLAB can be done with function handles . Essentially, this is an object pointing to a function. In your case, we in fact need an anonymous function handle :
L = @(k) sum( (k - in) + (in - k).*log(k - in) + k )
The variable in
is "frozen". For the anonymous function handle it is as if in
was hard coded. The @
indicates a function handle and the followed (k)
denotes that the variable k
should be considered as the first input of this new function (this is why it is an anonymous function handle. The variable k
becomes and anonym input). So you could now call
L(10)
and would obtain
L = -17.7921
as before.
Now the optimization function can use this (note that you need to include the minus in the function handle, so we just wrap it in a new one:)
fnc = @(k) -L(k)
lb = 1+10-9; % lower bound
ub = 100; % upper bound
[k_opt,fval] = fminbnd(fnc ,lb,ub)
k_opt = 3.2835 fval = -32.5310
Be aware that your function becomes complex for values k <= 1
, which is why I have restricted the minimum bound here to larger values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.