% Enero 2020 -- Pedro González based on Froilán M. Dopico's script.
% Introducción del Libro NCM de C. Moler.
%

%
% Most important lesson today: Use Matlab Help.
%

phi = (1 + sqrt(5))/2

%

format long % Look for "format" in Matlab help and play with the different Matlab formats
phi

%

vpa(phi,50) %to show 50 decimal positions
phi = double(phi)

%

% Operations +,-,*,^

% Play a little bit with these operations over scalars

%

% Arrays (Matrices and vectors)

M = [1, 2, 3; 4, 5, 6]

M = [1 2 3
    4 5 6]

size(M)        % returns the dimensions of the array

M(1,2)  %para seleccionar es ()

M(1,2) = 7 %se cambia el elemento en (1,2) a 7

N = [M;M]; %para crear matrices es []

N % ; = rbind: es para poner una debajo de otra (en filas)

O = [M,M] % , = cbind: en columnas

v = -1:4  % or [-1:4] would be ok in this case (vector de -1 a 4)
v=-1:2:4 %vector de -1 a 4 de 2 en 2

w1 = [-1:4,7:12,123:126]
w2 = [-1:3;1:5;7:-1:3]

M(2,:) %all elements (:) of the second row
M(:,1) %all elements of first column

M(:) % What is this commmand doing? muestra las columnas una detras de otra

%

% Functions that define special arrays

S = zeros(3,4) %define a 3x4 matrix of 0

T = ones(2,5)  %define a 2x5 matrix of 1

I = eye(4)   %define a 4x4 identity matrix     

R = rand (4,2)  % generates a (4 x 2) matrix of random
                % variables uniformly distributed on the
                % interval (0.0,i.0)
L = linspace (-1, 5,7)  % generates a 7-element row vector of. = seq 
                        % equally spaced numbers between -1 and 5

% Array operations

M' %traspuesta

M*M'

M*M'

2*M
2.*M

M+M

%M+M'

M+2 


%

% Element by element operations

M.*M %multiplicar NO de forma matriz
M./M
M.^M

% Experiment with .+ ./ .^ (el + ya es element by element)

%

% Useful matrix functions

A = [1 2; 3 4]

det (A)  % determinant of a square matrix

inv (A)  % inverse of a square matrix

rank (A)  % rank of a matrix 

[V,D]=eig(A)  % eigenvectors and eigenvalues of a square matrix

poly (A)  % coefficients of characteristic polynomial of A

%

% You can define polynomials as vectors whose components are the
% coefficients of the polynomial.
p = [1 -1 -1] %= x^2-x-1
r = roots(p)
% Matlab has symbolic capabilities too:

syms x
r = solve(1/x == x-1)

%

% MATLAB Built-in Functions

help elfun

%

% Plots

% Most times we will not know the function explicitly, just some values

x = linspace (0, 2, 30) ; % create a vector of 30 values equally spaced between 0 and 2
y = x.*exp(-x) ;  % calculate the y values corresponding to the vector x
plot (x, y) % plot y versus x
grid % add grid lines to the current axes
xlabel('Distance') % label the x-axis
ylabel('Concentration') % label the y-axis
title('Figure i- y = xe^-^x ') % add the title of the graph
gtext('anywhere') % place text with mouse
text(l,0.2, ' (i,0.2) ') % place text at the specific point

% Two plots in the same figure
plot(x, y, '+', x, x.*sin(x))

% More figures

figure(2)
plot(x, y, '+', x, x.*sin(x))
hold on
plot(x,cos(x),'ko')
hold off

axis([O, 1.5, O, 1.5])

% Multiple plots

figure
subplot(2,1,1), plot (x, x.*cos (x) )
subplot(2,1,2), plot (x, x.*sin (x) )

% Other useful 2D plots

plotyy(xl,yl,x2,y2) % plots xl versus yl with y-axis labeling on the left and plots x2 versus y2 with
                    % y-axis labeling on the right
                    
semilogx(x, y)     % semilogarithmic plot, x-axis is logarithmic
semilogy(x, y)     % semilogarithmic plot, y-axis is logarithmic
loglog(x, y)       % full logarithmic plot, both axes logarithmic

%

% Defining anonymous functions
f2 = @(x) 1/x - (x-1)
f2(1)
% If you know the function explicitly:
fplot(f2,[0,4])

%

% Vectorization
f = @(x) 1./x - (x-1)
f(1)
f([1 2])
[f2(1) f2(2)]

%

fplot(@(x) 1./x - (x-1),[0,4])
fplot(@(x) 1./x - (x-1),[0.2,4])

%

% same as
fplot(f,[0.2,4])
title('my first plot')
h2 = @(x,y) 2*x - y.^2 + 5
%h = @(x,y) 2.*x - y.^2 .+ 5 % This would not work, why?
h = @(x,y) 2.*x - y.^2 + 5 % It does work
h2([1 2 3],[4,5,6])

%

% preferred command for finding ONE zero of a single variable function
phi = fzero(f,1) 
hold on
plot(phi,0,'o')
hold off

%

% Scripts and functions

% ideal gas.m - A sample script file
% Calculates the volume of an ideal gas
%
clear; clc; %clear all previous variables and command window
disp(' Calculating the volume of an ideal gas.')
R = 8314; % Gas constant
T = input(' Vector of temperatures (K) = ');
P = input(' Pressure (bar) = ')*1e5;
V = R*T/P; % Ideal gas law

% Creating functions

%

function V = ideal_gas_func(T, P)
    % This function calculates the specific volume of an ideal gas
    R = 8314; % Gas constant
    for k = l-length(P)
        V(k, :) = R*T/P(k) ; % Ideal gas law
    end
end


%
% 1.- Write a function that plots an user defined ellipse for given long and short axes, and focuses.
% 2.- Write a script that calculates the least squares solution of Ax=b with A=[1 2;3 4;5 6] and b=[1,2,3].
% 3.- Write a script to build an upper (respectively, lower) triangular matrix of dimension 10 having 2 on the main diagonal and −3 on the second upper (respectively, lower) diagonal.
%      (Look for "diag" in the help).
% 4.- Write the MATLAB instructions which allow the interchange of the third and seventh row of the matrices built up in the previous exercise, and then the instructions allowing the     interchange between the fourth and eighth column.
% 5.- Verify whether the following vectors in R4 are linearly independent: v1 =[0 1 0 1], v2 =[1 2 3 4], v3 =[1 0 1 0], v4 =[0 0 1 1]. (What ways do you know to do it? Look for the keywords in the help).
%
%