% Portfolio Optimization:
% Problem Formulation & Solution

Aeq = ones(1,N);
beq = [1];             % Budget constraints.

lb = zeros(N,1);
ub = 0.2.*ones(N,1);   % Diversification constraints.  

w0 = zeros(N,1);
w0(N) = 1;             % Initial guess for the local optimizer.

options = optimset('LargeScale','off');   % Set options structure.


% Run the optimization:

[w,U,exitflag,output] = quadprog(lambda.*V, -r, [], [], Aeq, beq, lb, ub, w0,options);


% Display allocation, expected return, exitflag, and optimization output:

allocation = w 
pie3(allocation+eps)  % eps avoids divide by zero in plotting.
colormap(hsv(N))
colorbar
title('\bf{Optimal Asset Allocation}')

expected_return = r'*w

exitflag

output