MATLAB: Please, I have limited time for a project. I’ll like to know what this code does

optimization

variables = {'as','aw','ah'};
N = length(variables);
%create variables for indexing
for v = 1:N
eval([variables{v},' = ', num2str(v),';']);
end
%Defining the lower bounds
lb = zeros(size(variables));
lb([as,aw,ah]) = [0,0,0];
%Defining the upper bounds
ub = Inf(size(variables));
ub([as,aw,ah]) = [Ns,Nw,Nh];
%Entrying linear inequality constraints
A = zeros(2,3);
A(1,[as,aw,ah]) = [-Ps(i),-Pw(i),-Ph(i)];
b(1) = -P_load(i);
A(2,[as,aw,ah]) = [Ps(i),Pw(i),Ph(i)];
b(2) = P_max;
%Linear Equality Constraints
Aeq=[];
beq=[];
%Objective Function
f = zeros(size(variables));
f([as aw ah]) = [Cus*Ps(i)*T Cuw*Pw(i)*T Cuh*Ph(i)*T];
%Solving the problem with linprog
[x fval] = linprog(f,A,b,Aeq,beq,lb,ub);
for d = 1:N
fprintf('%12.2f \t%s\n',x(d),variables{d});
end;
aso(i)=x(1), awo(i)=x(2), aho(i)=x(3);
P_Supply(i)=aso(i)*Ps(i)+awo(i)*Pw(i)+aho(i)*Ph(i);
cost(i)=fval/P_Supply(i);

Best Answer

The code is very strange. It is overly complicated and near to be obfuscated.
Original:
variables = {'as','aw','ah'};
N = length(variables);
%create variables for indexing
for v = 1:N
eval([variables{v},' = ', num2str(v),';']);
end
Simplified (as Walter has posted already):
as = 1;
aw = 2;
ah = 3;
Original:
lb = zeros(size(variables));
lb([as,aw,ah]) = [0,0,0];
ub = Inf(size(variables));
ub([as,aw,ah]) = [Ns,Nw,Nh];
Simplified:
lb = zeros(1, 3);
ub = [Ns,Nw,Nh]; % The values of Ns, Nw and Nh do not appear in your code
Original:
A = zeros(2,3);
A(1,[as,aw,ah]) = [-Ps(i),-Pw(i),-Ph(i)];
b(1) = -P_load(i);
A(2,[as,aw,ah]) = [Ps(i),Pw(i),Ph(i)];
b(2) = P_max;
Simplified:
A = [-Ps(i),-Pw(i),-Ph(i); ...
Ps(i),Pw(i),Ph(i)];
b = [-P_load(i), P_max];
But notice, that "i" is not defined in the posted code.
Original:
%Objective Function
f = zeros(size(variables));
f([as aw ah]) = [Cus*Ps(i)*T Cuw*Pw(i)*T Cuh*Ph(i)*T];
Simplified:
f = [Cus*Ps(i), Cuw*Pw(i), Cuh*Ph(i)] * T;
Seeing the original code let me assume, that the author does not want the program to be understandable on purpose. The missing variables i,Ns,Nw,Nh let me think, that this program will not run at all. The actual command linprog(f,A,b,Aeq,beq,lb,ub) is not reached.
Related Question