フィルターのクリア

How to pass additional inputs to function in 'fminbnd'?

3 ビュー (過去 30 日間)
Abhinav
Abhinav 2018 年 2 月 5 日
編集済み: Stephen23 2020 年 3 月 19 日
I have a function to optimize with respect to 'lambda':
function v = minfunction(lambda)
data = xlsread('data.xlsx');
data = data(:,2:3);
idx = xlsread('idx.xlsx');
v = 0;
for i = 1:size(idx,1)
v = v + max(0,(lambda*data(idx(i,1),1)+(1-lambda)*data(idx(i,1),2)-(lambda*data(idx(i,2),1)+(1-lambda)*data(idx(i,2),2))));
end
end
The optimization is of following form
lambda = fminbnd(@minfunction,0,1)
However, the function 'minfunction' asks for other arguments 'data' and 'idx'. These matrices are updated after each iteration. Currently, I am using excel data to pass these arguments. But I want to pass arguments 'data' and 'idx' in the 'minfunction' it self. If I am writing
function v = minfunction(data,idx,lambda)
and calling the optimizer as
lambda = fminbnd(@minfunction,0,1)
the MATLAB is showing error as too many input arguments.
Can someone help me with this? I am attaching the excel files with question containing idx and data.

採用された回答

Stephen23
Stephen23 2018 年 2 月 5 日
編集済み: Stephen23 2020 年 3 月 19 日
Do NOT call xlsread inside the function! Doing so will result in slow and inefficient code due to repeated file access.
The proper solution to your question is to define your function with as many arguments as you require:
function v = minfunction(data,idx,lambda)
and then pass it to the optimizer using an anonymous function:
idx = ...
lam = ...
v = fminbnd(@(t)minfunction(t,idx,lam), 0, 1);
Using this method the values of idx and lam are defined just once, and are then used for all iterations of the optimizer. You can read more this method by reading the MATLAB documentation:
  4 件のコメント
Jiri
Jiri 2020 年 3 月 5 日
Thanks Stephen, I needed the same answer.
ahmed elakhdar
ahmed elakhdar 2020 年 3 月 18 日
lambda = fminbnd(@(lambda)minfunction(data,idx,lambda),0,1)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProblem-Based Optimization Setup についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by