Matlab Code for Week 6
Contents |
MATLAB Code: Setup for CVX
%% setup for class examples % first go to the cvx directory and run cvx_setup
MATLAB Code: Optional for the following examples
%% tell cvx to be quit s_quiet = cvx_quiet(true); s_pause = cvx_pause(false); cvx_clear; echo on has_quadprog = 0;
MATLAB Code: Example 1: LEAST SQUARES
% Input data m = 16; n = 8; A = randn(m,n); b = randn(m,1); % Matlab version x_ls = A \ b; % cvx version cvx_begin variable x(n); minimize( norm(A*x-b) ); cvx_end echo off plot(1:m, A*x, 1:m, b) xunc = x;
MATLAB Code: Example 2: BOUND-CONSTRAINED LEAST SQUARES
% Input data m = 16; n = 8; %A = randn(m,n); %b = randn(m,1); % More input data bnds = randn(n,2); l = min( bnds, [] ,2 ); u = max( bnds, [], 2 ); % cvx version cvx_begin variable x(n); minimize( norm(A*x-b) ); subject to x >= l; x <= u; cvx_end echo off figure(2), plot(1:n, x, 1:n, u, 1:n, l) hold on, plot(1:n, xunc), hold off figure(4), plot(1:m, A*x-b, 1:m, A*xunc - b); norm(A*x-b), norm(A*xunc - b),
MATLAB Code: Example 3: Infinity Norm
% Input data m = 16; n = 8; A = randn(m,n); b = randn(m,1); % cvx version cvx_begin variable x(n); minimize( norm(A*x-b,Inf) ); cvx_end echo off figure(1), plot(A*x-b) %% compare to unconstrained % cvx version cvx_begin variable xu(n); minimize( norm(A*xu-b) ); cvx_end figure(2), plot(1:m,A*x-b, 1:m, A*xu-b)
MATLAB Code: Example 3: One Norm
% cvx version cvx_begin variable x(n); minimize( norm(A*x-b,1) ); cvx_end