フィルターのクリア

Using a meshgrid or vector inside all function

1 回表示 (過去 30 日間)
hossein
hossein 2018 年 10 月 11 日
コメント済み: hossein 2018 年 10 月 11 日
Hi
I am trying to run an optimization on a 2 variable f(x,y) function inside a region. This region is defined by a mesh-grid of points. Since this grid of points is not changed in every iteration of the optimization, I like to define this mesh grid before the optimization commands and outside my cost function so that the cost function has only unknown variables as input while inside it I can used the grid variable. I would like to do this:
global a a=[1 2 3] %the grid data here
and then the cost function of the optimization algorithm is like this: function out=costfun(x) out=x(1)*a(1)+x(1)*a(1)+...
but it does not work. every time the function is called, the global a variable is now know to it. I should give this grid to the function as input. what can I do about it? Thanks in advance

採用された回答

Honglei Chen
Honglei Chen 2018 年 10 月 11 日
You need to put
global a
in your cost function too. See the example in
HTH
  3 件のコメント
Honglei Chen
Honglei Chen 2018 年 10 月 11 日
I'm trying to illustrate how global should be used in MATLAB. For a function to see the global variable, you need to add the global declaration in the function. It's a declaration, you don't need to redefine it.
hossein
hossein 2018 年 10 月 11 日
Oh. sorry. Now I got what you meant. 1- define the grid before the function as a global var and assign values to it. 2-call the function without the grid as the input. 3-use "global a" command inside the function to declare the previously defined a.
I tested it and it worked. Thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by