Can I edit and change the value of global variables inside the called functions?

11 ビュー (過去 30 日間)
Ehsan Asadi
Ehsan Asadi 2013 年 3 月 7 日
Hi,
I am doing some optimization and I have 3 *.m scripts:
1- main
2- cost function
3- constraints function
------------
In the main function I define some global variable so I can use them inside the cost function. To calculate the constraints function values, I need to use a number (k) that is obtained in the middle of cost function calculations (k is not its output). I can calculate (k) again in the constraints function but it a waste of cpu time. So as a solution, can I set it as global variable in the main file and set a temporary value to it and later in the cost function edit its value so it can be used in constraints function?
in simple words:
1- main>>>> setting global k; k=0;
2- cost function>>>> global k; calculate the exact k
3- constraints function>>> global k, use the k to find the constrains!
Thank you Ehsan Asadi

回答 (2 件)

Jan
Jan 2013 年 3 月 7 日
編集済み: Jan 2013 年 3 月 7 日
This works reliably, when you can be absolutely sure, that the cost function is called with exactly the same parameters as you need in the following constraint-function call.
An optimizer could call the cost function repeatedly to get an approximation its 2nd derivative (e.g. to estimate the size of the variation to obtain the 1st derivative). Then that last call to the cost function can contain completely different parameters than the following call of the constraint function.
If the calculation of k is very expensive (seconds or more), it can be useful to store a fingerprint of the parameters (see e.g. <http://www.mathworks.com/matlabcentral/fileexchange/31272-datahash FEX: DataHash) and re-use the value of k only, if the hash of the parameters is equal.

Alan Weiss
Alan Weiss 2013 年 3 月 7 日
This is similar to new documentation on evaluating an objective and nonlinear constraints in the same routine. Perhaps that documentation can give you another way of handling your case without using any global variables.
Alan Weiss
MATLAB mathematical toolbox documentation

カテゴリ

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