## How to redefine a variable inside the function?

Rustem Devletov

### Rustem Devletov (view profile)

さんによって質問されました 2019 年 4 月 30 日

### Walter Roberson (view profile)

さんによって コメントされました 2019 年 5 月 6 日
Torsten

### Torsten (view profile)

さんの 回答が採用されました
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)

#### 0 件のコメント

サインイン to comment.

## 1 件の回答

2019 年 4 月 30 日

### Torsten (view profile)

2019 年 4 月 30 日
採用された回答

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.

Rustem Devletov

### Rustem Devletov (view profile)

2019 年 5 月 6 日
okay, sir. I'll try to do that, but I'm new to matlab. If I have questions, can I ask you too?
Rustem Devletov

### Rustem Devletov (view profile)

2019 年 5 月 6 日
Thank you a lot, Torsten, Walter Roberson, Stephen Cobeldick!!! Everything works now
Walter Roberson

### Walter Roberson (view profile)

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.

サインイン to comment.