%% examples classs 29/9/2017

% comment the file with symbol %
%% 1 rad2deg
clear all %clear previously defined variables
clc % cleans up the operation screen

rad2deg=180/pi; %the command ; means it does not print 
                %on the operation screen the answer

b=asin(sqrt(3)/2)*rad2deg

format long
b

%% storing of matrices and vectors
clear all
clc
format short

a=[3 5 9 2 11 7]

b=[3; 5; 9; 2; 11; 7]

% in order to access values i use indices
% N.B. ONLY NATURAL NUMBERS!!!!!!!!!!!

a(3)
b(3)

%a(2.1) % WRONG!!!

% in order to store a MATRIX

M=[1.3 5.2 9.3; 4.2 4.5 6.1]
size(M)
% matrix transposition
N=transpose(M);
% or equivalently
N1=M.';

% accessing to elements
M(1,1)
% is equivalent to
M(1)

M(2,1)
% is equivalent to
M(2)

M(1,2)
% is equivalent to
M(3)

M(2,2)
% is equivalent to
M(4)

M(1,3)
% is equivalent to
M(5)

% : command for indices!
m=M(:)

m1=M(1:3)

M(1:1,:)

% command find
index=find(M>=5.2)
size(index)
M(index)

%% matrix and vector operations
% MATHEMATICAL
clear all
clc

M=[4 2 1; 5 9 12];
a=[1; 2; 3];

b=M*a

transpose(a)*transpose(M)
% same as
b.'

N=[5 1; 3 2; 5 6];

transpose(a)*N

%% exercise 2.1.2
clear all
clc
format long

a=[1.5 6.2 4.4];
b=[2.1 9.4 7.1];

% scalar product
dot(a,b)

% or equivalently
a*(b.')

% angle between them
theta=acos( dot(a,b)/(norm(a)*norm(b)) )
% this is equivalent to
asin( norm(cross(a,b))/(norm(a)*norm(b)) )

%% component-wise multiplication (does nor corresponds to a mathematical op)
%
clear all
clc

a=[1 2 3 4 5];
a.*a

% equivalent to
a.^2

%plot(a,a.^2)

M=[1 2 3 4 5; 6 7 8 9 10];

M.*M
% but i CANNOT DO  M.*transpose(M)

%% how to plot functions
% first we defne a grid of N points equally spaced 
% on the interval [a,b]
clear all
close all
clc
format short
a=0; b=1; N=5;
x=linspace(a,b,N)

dx=x(2)-x(1)
% is the same as
(b-a)/(N-1)

% or equivalently
xp=(a:dx:b)

f=x.^2;
figure(1)
hold on
plot(x,f,'s-')
xlabel('x')
ylabel('f(x)=x^2')
hold off

N=100;
x=linspace(a,b,N)
f=x.^2;
figure(2)
hold on
plot(x,f,'--')
xlabel('x')
ylabel('f(x)=x^2')
hold off


%% excercise 4.0.4
clear all
close all
clc
a=0; b=10; N=200;
x=linspace(a,b,N);
% carefull that exp(-x) is a raw vector with 200 components!!
f=x.*exp(-x);

figure()
hold on
plot(x,f,'or-')
plot(x,x,'b--')
plot(x,exp(-x),'g--')
plot(1,exp(-1),'sc','MarkerSize',12,'LineWidth',2)
xlabel('x')
ylabel('f(x)')
axis([a, b, 0, 0.4])
hold off

%% subplots
% excercise 4.0.5
clear all
close all
clc
tin=0; tfin=10*pi; N=500;
t=linspace(tin, tfin, N);

A=1; w=1; v=1;
x=v*t+A*cos(w*t);

subplot(2,2,1)
hold on
plot(t,x,'r')
plot(t,v*t,'b--')
xlabel('t')
ylabel('x(t)')
title('A=1,w=1, v=1')
legend('x(t)','v*t','Location','NorthWest')
hold off




