I have a cost function hybrid_cost() defined for optimization. Howver, with N defined, the function hybrid_cost() on running shows -
Undefined function or variable 'N'
Even after declaring N as global, the problem persists.
N=4;
function cost=hybrid_cost(x)
cost=0;
T1=0;
q=zeros(N);
q(1,1)=x(1);
q(N,N)=x(2);
M=create_M(x);
Ai=M+q;
A=zeros(N);
for i=1:P
A=Ai+eyes(size(M,1))*st(i);
c=abs(cof(A,1,N))^2;
T1=T1+c;
end
T1=4/(q1*qn) * T1;
cost=T1;
end

답변 (1개)

KSSV
KSSV 2020년 5월 23일

0 개 추천

N=4;
function cost=hybrid_cost(x,N)
cost=0;
T1=0;
q=zeros(N);
q(1,1)=x(1);
q(N,N)=x(2);
M=create_M(x);
Ai=M+q;
A=zeros(N);
for i=1:P
A=Ai+eyes(size(M,1))*st(i);
c=abs(cof(A,1,N))^2;
T1=T1+c;
end
T1=4/(q1*qn) * T1;
cost=T1;
end
The variable N, should be passed to a function as shown above. Though you have defined the variable outside the function, it cannot be found inside the function unless you declare N as gloabal variable.

댓글 수: 5

Divyayan Dey
Divyayan Dey 2020년 5월 23일
The problem with passing N as a function input is that,this is a cost function for optimization. And its inputs are all control variables. Passing N as a input will make the optimizer consider N to be an input when it is a constant for optimization.
Even after declaring N as global,the problem still persists.
Stephen23
Stephen23 2020년 5월 23일
"The problem with passing N as a function input is that,this is a cost function for optimization."
That is not a problem: just parameterize the function.
"Passing N as a input will make the optimizer consider N to be an input when it is a constant for optimization."
Not when you parameterize the function:
Divyayan Dey
Divyayan Dey 2020년 5월 23일
Why does the problem persist with global declaration of variables? I won't be able to parameterize every function with nesting because that would make my code too lengthy.
Stephen23
Stephen23 2020년 5월 23일
"I won't be able to parameterize every function with nesting"
There are two methods shown in the documentation for parameterizing functions: nested functions and anonymous functions. Have you tried using anonymous functions as the documentation shows?
Divyayan Dey
Divyayan Dey 2020년 5월 23일
Thanks. That worked.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터 및 File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기

질문:

2020년 5월 23일

댓글:

2020년 5월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by