Question:
Find the optimal state and optimal control based on  minimizing the performance index  𝐽=∫ (𝑥(𝑡) − 1/2 (𝑢(𝑡)^2) ) 𝑑𝑡  , 0 ≤ 𝑡 ≤ 1 subject to 𝑢(𝑡) = 𝑥̇(𝑡) + 𝑥(𝑡) with the condition  𝑥(0) = 0, 𝑥(1) = 1 2 (1 − 1 /e )^2 where 𝐽𝑒𝑥𝑎𝑐𝑡 = 0.08404562020 In this example the initial approximation is  𝑥1 (𝑡) =  1/2 (1 − 1 /e ) ^2
My finding: 
I saw there are warnings in global variables and was thinking of alternative of global variables. Please explain this giving an example. 
ERROR:
 solve_system_of_equations
Error using fmincon (line 641)
Supplied objective function must return a scalar value.
Error in solve_system_of_equations (line 40)
x = fmincon(fun,x0,A,bb,Aeq,beq,lb,ub);
CODE:
function F = cost_function(x)
global def;
global m;
s=def.k ;
C2=x(1,(s+1):2*s);
u=(C2*m.H)   ;
F= x - 1/2*(u*u');
    function F = system_of_equations(x)
        global def;
        global m;
        global init;
        
        global P_alpha_1;
        s=def.k ;
        
        C1=x(1,1:s);
        C2=x(1,(s+1):2*s);
        
        
        x1=(C1*P_alpha_1*m.H) + init(1);
        u=(C2*m.H)   ;
        D_alpha1_x1= C1*m.H;
        %     
        M=Haar_matrix(s);
        HC=M(:,s);
        
        %%control law1
        F = horzcat(  D_alpha1_x1   + x1 - u  , ...
            (C1*P_alpha_1*HC) + init(1) - (1/2*((1-exp(-1))^2)))     ;
        
    end
alpha_1=1;
k=8;     %no. of Haar wavelets 
b=2;  %Total number of days to plot
initialize(alpha_1,k,b )
global m;
global init;
global def;
global P_alpha_1;
global P_alpha_2;
P_alpha_1=fractional_operation_matrix(k,alpha_1,b,m.H);
s=def.k;
x0=zeros(3,3*s);
%  system_of_equations(x)
A = [];
bb = [];
Aeq = [];
beq = [];
lb = [];
ub = [];
fun = @cost_function;
nonlcon=@system_of_equations;
x = fmincon(fun,x0,A,bb,Aeq,beq,lb,ub,nonlcon)