www.gusucode.com > GAVPai_Book_MathworksCntrlFileEx_May2019 > GAVPai_Book_MathworksCntrlFileEx_May2019/min_var_cnstrobjfun.m

      % Chapter 1  : Equation [1.22]
  % Objective: to obtain optimal weights of the portfolio that yields
  % minimum risk for the given expected portfolio return,  using quadratic programming
  %------------------------------------------------------------------
  %Inputs: Portfolio size (portfolio_size), mean returns of assets (mean_data), covariance of returns (cov_data),
  %        given expected portfolio return (R) 
  %Output: Optimal weight set of the minimum risk portfolio for the given
  %        expected portfolio return (var_x), 
  %        minimal risk value (min_obj_fun_val)
  
  function [var_x,  min_obj_fun_val]= min_var_cnstrobjfun(portfolio_size, mean_data, cov_data, R)

  
  clear H  f  Aeq  beq  lb  ub;
  echo off
  H=2*cov_data;                               % matrix H
  f=zeros(portfolio_size, 1);                 % vector f
  
  % Aeq and beq represent equality constraints
  Aeq= [ones(1, portfolio_size); mean_data];  
  beq=[1;R];
  
  % lb and ub, lower and upper bounds for variables xi
  lb=zeros(1, portfolio_size);                
  ub=ones(1, portfolio_size);
  
  % obtain optimal weights using quadratic programming
  [var_x,min_obj_fun_val] = quadprog(H,f,[],[],Aeq, beq, lb,ub);
  end