How to redefine a variable inside the function?

21 次查看(过去 30 天)
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 个评论
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