How to redefine a variable inside the function?

조회 수: 3 (최근 30일)
Rustem Devletov
Rustem Devletov 2019년 4월 30일
댓글: Walter Roberson 2019년 5월 6일
The problem is that the variable x13 has its input value, but every further iteration it should change. The code I've written uses its initial value every iteration, and I don't know how to redefine it correctly. I understand where the mistake is, but help me to fix it please
file 1
function [Q, y11, y12, y21, y22, y33]= myfun(x)
k1=3;
k2=6;
alpha1=0.3;
alpha2=0.3;
x12=10;
V1=x(1);
V2=x(2);
x13=x(3); %this variable gets its value from the array x in the file 2, but it has to be redefined further
C1=10; %cost 1
C2=15; %cost 2
C3=24;%cost 3
y11=(x12+x13)/(x12+x13+k1*V1);
y12=x12+x13;
x22=y12;
x21=y11;
y21=x22*x21/(x22+k2*V2);
y22=x22;
x31=y21;
x32=y22;
y33=x31*x32;
x13=y33; % It should be redefined here, and the same thing should happen in the every further iteration.
Q=C1*V1^alpha1+C2*V2*alpha2+C3*x32;
file 2
clear all
clc
fun = @myfun;
x = [20,30, 15];
A = [];
b = [];
Aeq = [];
beq = [];
lb = [5, 10];
ub = [15, 20];
nonlcon = [];
options = optimoptions('fmincon');
[x,fval,exitflag,output] = fmincon(fun,x,A,b,Aeq,beq,lb,ub,nonlcon,options)
Another interpretation, but the same problem
file 1
function [Q, y11, y12, y21, y22, y33]= myfun(x)
k1=3;
k2=6;
alpha1=0.3;
alpha2=0.3;
x12=10;
x13=15; % I assign the value to x13 here
V1=x(1);
V2=x(2);
C1=10; %cost 1
C2=15; %cost 2
C3=24;%cost 3
y11=(x12+x13)/(x12+x13+k1*V1);
y12=x12+x13;
x22=y12;
x21=y11;
y21=x22*x21/(x22+k2*V2);
y22=x22;
x31=y21;
x32=y22;
y33=x31*x32;
x13=y33; %it gets redefined here
Q=C1*V1^alpha1+C2*V2*alpha2+C3*x32;
file 2
clear all
clc
fun = @myfun;
x = [20,30];
A = [];
b = [];
Aeq = [];
beq = [];
lb = [5, 10];
ub = [15, 20];
nonlcon = [];
options = optimoptions('fmincon');
[x,fval,exitflag,output] = fmincon(fun,x,A,b,Aeq,beq,lb,ub,nonlcon,options)

채택된 답변

Torsten
Torsten 2019년 4월 30일
편집: Torsten 2019년 4월 30일
Add the nonlinear constraint
x(3) - x31*x32 = 0
in function "nonlcon".
And remove the lines
y33=x31*x32;
x13=y33; % It should be redefined here, and the same thing should happen in the every further iteration.
at the end of "myfun".
And "myfun" must have only one return parameter (namely the value of the objective function), not six as in your code.
  댓글 수: 21
Rustem Devletov
Rustem Devletov 2019년 5월 6일
Thank you a lot, Torsten, Walter Roberson, Stephen Cobeldick!!! Everything works now
Walter Roberson
Walter Roberson 2019년 5월 6일
Stephen, lb and ub are adjusted to match the size of x0; the number of variables is never derived from lb and ub.
x0 was given as [20, 30] which is only two values.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Programming and Mixed-Integer Linear Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by