clear all; close all;
% see homework i for how to publish the matlab script
% all of the following formatting of comments etc. is done so that the
% published  output looks correct. 

%% This is how you define sections
%%
% * a) this is how you define sub-sections
%%
% * indexing, vectors, matrices, variables
a = [1,2,3];
b = [1;2;3];
who 
whos a
%% 
% comment this is how you print text answers that you want us to see in the
% published mode. we see from the code above that a is a row vector and b
% is a column vector

%% 
% you can define vectors also by pre-allocating using zeros, rand, ones,
% etc. and then filling in values
a = zeros(1,3);
a(1) = 1;
a(2:3) = [2,3];

% matrices

A = rand(3);
% grab column 2 from A
A(:,2)

% logical indexing: why might we want to index using logicals? Selecting
% elements based on properties or values! See below for example

% get all elements > 0.5
A(A>0.5)

% useful function related is find this will return the indices
find(A>0.5)

% can also get the logical array 
A > 0.5

% other logical operators include >, ==

% A is a 
x = [4,-1]

scaledx = 2*x
%%
% * plotting
figure;

% one way to plot a vector is using plot (specifying the origin)
% this does not put an arrow at the end
plot([0, x(1)],[0,x(2)])

% to get an arrow plot we use quiver
figure;
quiver(0, 0, scaledx(1), scaledx(2), 0)


%% Computing vector information
% * b)
lengthx = sqrt(x*x')
% can also calculate length using simple ops
lengthx = sqrt(sum(x.^2))
unitx = x/lengthx
%% Computing the dot product and angles
y = [1,4];
lengthy = sqrt(y*y');
dot(x,y)
costheta = (x*y')/(lengthx*lengthy)

figure;
hold on;
quiver(0,0,x(1), x(2), 0)
quiver(0,0,y(1),y(2),0)
title('Plotting Vectors')
xlabel('x')
ylabel('y')
legend('x', 'y')

% important! we need axis equal to show the vectors are actually orthogonal
axis equal

%%
% the cosine of the angle is 0 (as is the dot product) meaning the vectors
% are orthogonal
%% Projections

y = [3,2];


% compute length of projection of y onto x
% compute the vector projection of y onto x
% plot x, y, and projection of y onto x 
% compute cosine of angle between x,y 
% plot x and y on the same plot using quiver and hold
lengthy = sqrt(y*y');
costheta = (x*y')/(lengthx*lengthy)
projscalar = lengthy*costheta
projscalar = (unitx*y');
projvector = projscalar*unitx;

% we need the diff vector to plot the perpendicular line for distance
% between the two vectors (shortest line). 
diffvector = y-projvector;
figure;
hold on;
quiver(0,0,x(1), x(2),0,'LineStyle','-')
quiver(0,0,y(1),y(2),0,'LineStyle', '-')
quiver(0,0,projvector(1), projvector(2),0)
quiver(projvector(1), projvector(2),diffvector(1),diffvector(2),0,'--')
title('Projections')
xlabel('x')
ylabel('y')
lgd=legend('x','y', 'proj y onto x', 'distancetoline')
lgd.Location = 'east'
axis equal

