%% Matlab code for in class examples, 6.3: %% The orthogonal decomposition theorem: % Let u1, u2 be given as the span of W (they are orthog), and let y be as % given. Decompose y as the sum of two vectors- one is the orthog proj of % y into W, and the other is in W^perp % First, define the three vectors: u1=[3;0;1]; u2=[0;1;0]; y=[0;3;10]; % Compute the projection into the span of u1, u2- This is y_hat (or yhat) yhat=( (y'*u1)/(u1'*u1) )*u1 + ( (y'*u2)/(u2'*u2) )*u2; % z is computed as y-y_hat: z=y-yhat; % We can verify that z is in W^perp by seeing that z is orthog to both u1 % and u2: z'*u1; z'*u2; %% The distance between y and subspace W is the length of z: norm(z); % or equivalently, sqrt(sum(z'*z)) %% The projection of y into W using a matrix U U=[u1 u2]; %normalize the columns of U d=sqrt(sum(U.*U)) %This is a row vector whose elements are the norm of % each column. d1=repmat(d,3,1) U=U./d1; %The projection is: U*U'*y