function [ B_c_all, B_d_all, M_s_all, M_b_all, G_s_all, G_b_all ] = cvxfunction( L_g, L_c, lambda, p_b, p_s, t,a)

B_c = battery charging

B_d = battery discharging

M_s = selling to the regional market

M_b = buying from the regional market

G_s = selling to the outside grid

G_b = buying from the outside grid

%Initialization for CVX

bc_max=40; bd_max=40; % battery bounds

ms_max=185; mb_max=185; % regional market trading bounds

gb_max=500; % maximum energy to buy from outside grid

S_init=50; S_max=200; % states of the charge of battery

n=0.85; % battery efficiency

gamma=0.95; % transmission efficiency

c=0; % cost for producing energy by microgrid

w=30; v=10; % defining utility function parameters

Cf = [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1];

for i=1:t

for j=1:a

if (0<=L_c(i,j)) && (L_c(i,j)<=w/v)

D(i,j)=w*L_c(i,j)-0.5*v*L_c(i,j)^2;
elseif (w/v<L_c(i,j))
D(i,j)=w^2/2*v;

else

D(i,j)=0;

end

end

end

for j=1:a

D2=D(:,j);

L_g_a=L_g(:,j);

L_c_a=L_c(:,j);

Lc_min=min(L_c_a);

Lg_max=max(L_g_a);

```
cvx_begin
variables B_c(t) B_d(t) M_s(t) M_b(t) G_s(t) G_b(t);
for i=1:t
X(i) = D2(i) - c*L_g_a(i) + gamma*p_s(i)*G_s(i) - p_b(i)*G_b(i) + lambda(i)*(gamma*M_s(i)-M_b(i));
end
maximize( sum(X) )
subject to
Lc_min-L_c_a<=0;
-L_g_a<=0;
-B_c<=0;
-B_d<=0;
-M_s<=0;
-M_b<=0;
-G_s<=0;
-G_b<=0;
L_g_a-Lg_max<=0;
B_c-bc_max<=0;
B_d-bd_max<=0;
M_s-ms_max<=0;
M_b-mb_max<=0;
G_b-gb_max<=0;
Cf * G_s == 0;
for i=1:t
t_B_c = B_c(1:i);
t_B_d = B_d(1:i);
-S_init-sum(n*t_B_c-t_B_d)<=0;
S_init+sum(n*t_B_c-t_B_d)-S_max<=0;
end
L_c_a-L_g_a+B_c-B_d+M_s-M_b+G_s-G_b <= 0.0000000001;
L_c_a-L_g_a+B_c-B_d+M_s-M_b+G_s-G_b >= -0.0000000001;
cvx_end
clear X
```

end

end

**Note:** I would like to add inside the cvx code, a script that prevents selling while buying and/or charging while discharging for the same agent