%% 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB
%% Part  5 - Visualization and Programming
%%
% This is the fifth MATLAB live script of the collection 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB, devoted to introduce the MATLAB environment and tools for solving practical problems related to the topics of the 034IN course, i.e. performance analysis of dynamic systems, design of control law for continuous-time linear dynamical systems, approximate discretization of a continuous-time control law etc.
% Use this link to go back to the main live script of the collection.
%
% Table of Contents
% 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB
% Part  5 - Visualization and Programming
%     Objectives
%     Visualization: An Introduction
%         With a Little Help from the 'help' Command!
%         A Simple Example
%         Another Example: 3D Line Plot
%     Programming: An Introduction
%     With a Little Help from the 'help' Command!
%     Polynomials in MATLAB
%             Introduction
%             Important Remarks
%             Examples
%             Evaluation of Polynomials
%             Roots of a Polynomial
%             Fundamentals Operations with Polynomials
%             Integrating and Differentiating Polynomials
%     Functions: The General Syntax
%         An Example
%     Functions Applied to a Vector
%         Examples
%     Summary
%             Back to the Index
%             Back to the Previous Part: Symbolic Maths Computations
%             Go to the Next Part: LTI Systems
%% Objectives
%  The aim of this live script is to illustrate
% how to visualize data
% how to create structured code in MATLAB,
% how to define and manage polynomials,
% how to use functions and to define custom function.
% What you should know by the end of this module:
% how to compute the roots of a polynomial; how to multiply or divide polynomials;
% how to call functions provided as part of MATLAB;
% use of input and output arguments;
% how to create a custom MATLAB function.
%
%% Visualization: An Introduction
%
% Being able to visualize the solution of a differential equation (linear, with constant coefficients), the evolution over time of an LTI system starting from assigned initial conditions and subjected to various external stimuli, or the system's frequency response, will allow us to obtain a lot of useful information about the dynamic system we are analyzing.
% How then can we visualize data in MATLAB?
%
%% With a Little Help from the 'help' Command!
% Here is a list of the main categories of topics, available with the help command, related to the visualisation of data using MATLAB
% Two dimensional graphs

help graph2d

% Three dimensional graphs

help graph3d

%
% More information about data visualization using MATLAB is available online
% https://it.mathworks.com/discovery/data-visualization.html
% The "Visualizing Data in 2 D and 3D " module in the self-paced online course MATLAB Fundamentals.
%
%
%% A Simple Example
% Consider the variable
% y(t) = \left[ 1-\displaystyle e^{-\left(\frac{t}{\tau}\right)} \right]
% where the time constant \tau is
% \tau = 1.5 \;\text{days}
% Create a row-vector tVec that has 10000 samples  between 0 and 648000 seconds.
% Hint: use the command linspace.
% Evaluate y(t) for each of the time instant t in tVec.
% Display the graph of the function using the 10000 samples just calculated.
%

clear % clean the MATLAB workspace
close all
clc

Tau_days = 1.5;

secPerDay = 60*60*24;
tau = Tau_days * secPerDay;

% let's define the time row array tVec
startT = 0;
endT = 648000; 
Nsamples = 10000;

tVec = linspace(startT, endT, Nsamples);

% evaluate the function using the time row-vector
y_vals = (1-exp(-tVec/tau));

figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot(tVec, y_vals, 'LineStyle','-', 'LineWidth', 2.5);
grid on
xlim([min(tVec), max(tVec)]);
xlabel('time $t$ [s]', 'Interpreter', 'latex', 'FontSize',14);
ylabel('function $y(t)$', 'Interpreter','latex', 'FontSize',14);

%
% How to display more than one function graph in the same window?

tau2 = 2* tau;
tau10 = tau*10;
tau10th = tau/10;

% evaluate the functions using the time row-vector
y_vals2 = (1-exp(-tVec/tau2));
y_vals10 = (1-exp(-tVec/tau10));
y_vals10th = (1-exp(-tVec/tau10th));

figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot(tVec, y_vals, 'LineStyle','-', 'LineWidth', 1.5);

hold on; % we can now insert more graphs without deleting the previous ones

plot(tVec, y_vals2, 'LineStyle','--', 'LineWidth', 1.5);
plot(tVec, y_vals10, 'LineStyle','-.', 'LineWidth', 1.5);
plot(tVec, y_vals10th, 'LineStyle',':', 'LineWidth', 1.5);

% Note: A different line style is selected for each graph. 
% The color of each graph was chosen automatically, 
% cycling through 8 available colors (use the 
% help plot command for more information).

grid on

xlim([min(tVec), max(tVec)]);
xlabel('time $t$ [s]', 'Interpreter', 'latex', 'FontSize',14);
ylabel('function $y(t)$', 'Interpreter','latex', 'FontSize',14);

legend('$\tau = \bar \tau$', '$\tau = 2 \bar \tau$',...
        '$\tau = 10 \bar \tau$', '$\tau = \bar{\tau}/10$', ...
        'Interpreter', 'latex', 'FontSize', 14, ...
        'Location', 'best')

%
%
%% Another Example: 3D Line Plot
%

time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;

figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot3(x,y,z,'k','LineWidth',2);
grid on
zlabel('Time');ylabel('y'); xlabel('x');

%
% Use tools on figure to rotate it
% Can set limits on all 3 axes
% help xlim
% help ylim
% help zlim
%
%
%% Programming: An Introduction
%
% Functions are an essential mechanism for grouping a sequence of frequently used MATLAB commands to perform a specific task. Examples include all the standard mathematical functions such as sin, cos, tan, exp, log, sqrt, abs and many others. MATLAB also offers the possibility of defining custom functions. In this live script, we will only look at the simplest way of doing this, using anonymous functions. This is essential for problems such as solving non-linear equations, integrating a function and minimizing or maximizing a function. One of the great powers of MATLAB is the ability to apply functions to vectors and matrices with any number of elements in a single call.
%
%% With a Little Help from the 'help' Command!
% Here is a list of the main categories of topics, available with the help command, related to general purpose commands, operators and special characters, programming language constructs, character strings, file input/output, time and dates
% General purpose commands

help general

% Operators and special characters

help ops

% Programming language constructs

help lang

% Character strings

help strfun

% File input/output

help iofun

% Time and dates

help timefun

%
% Refer to the online courses on MATLAB Onramp,  MATLAB Fundamentals and MATLAB Programming Techniques for more information.
%
%
%%
% Here is a list of the main categories of topics, available with the help command, related to the predefined and custom functions
% Elementary math functions

help elfun

% Specialized math functions

help specfun

% Interpolation and polynomials

help polyfun

% Function functions and ODE solvers

help funfun

%%
%
%% Polynomials in MATLAB

clear variables

%% Introduction
% To represent polynomials, MATLAB uses numeric row vectors, which contain the coefficients of the polynomial, ordered by decreasing power.
% For example, the polynomial
% p(x) = 4\,x^5+ 8\,x^4+15\,x^3+16\,x^2+23\,x+42
% corresponds to the MATLAB row vector

p = [4, 8, 15, 16, 23, 42];

%%
%% Important Remarks
% The number of elements in a row-vector representing a polynomial is always n+1, where n is the degree of the polynomial itself.
% Intermediate terms of the polynomial with a null coefficient must also be included in the vector, since 0 acts as a placeholder for that particular monomial of x.
%% Examples
%
% The representation in MATLAB of the polynomial q(x) = x^4-4\,x^3+3x^2-x+12 is the row-vector

q = [1  -4  3  -1  12];

degree_q = numel(q)-1

% The row vector

px = [4  -4  1];

% corresponds to the second order polynomial p(x) = 4\,x^2-4\,x+1.
%
% Given the polynomials
% \tilde{p}(x) = 3\,x^3+81 \qquad \bar{q}(x) = 42\,x^4+16\,x^2+4
% the corresponding descriptions in MATLAB are the row vectors

p_tildeX = [3  0  0  81];

bar_qX = [42  0  16  0  4];

%
%
%% Evaluation of Polynomials
% Given the description of a polynomial p(x), how can the polynomial be evaluated at a specific value? For example, how do we compute p(42)?
% p(x) =  x^4-4\,x^3-x \qquad \qquad p(42) = ?
% Use the MATLAB command polyval:

clear p

p = [1  -4  0  -1  0]; % the coefficient of the polynomial p(x)

xVAL = 42; 
pVAL = polyval(p, xVAL)

%
%% Roots of a Polynomial
%
% Given the polynomial p(x), described by means of the row vector containing the polynomial coefficients, you can determine the roots of p(x) using the MATLAB command roots:
% p_1(x) = x^2-x-6

p1 = [1  -1  -6];
roots(p1)

%
% p_2(x) = x^4-4\,x^2+4


p2 = [1  0 -4  0  4  ];
roots(p2)

%
% What about the inverse problem? Given the roots of a polynomial, how can you determine the coefficients' vector?
% Use the MATLAB function poly:

clear px

px = [3  0  24  0  48];
r_px = roots(px)

px_1 = poly(r_px)

%
%% Fundamentals Operations with Polynomials
%
% Adding or Subtracting Polynomials
% Remember: you can add and subtract any polynomials, but only combine terms (monomials), which must have the same degree (exponent) [of course they must also have the same variable base]. Thus, how have these rules been applied when using the MATLAB numeric notation for polynomials? Obviously, they became rules on addition and subtraction of row vectors!
%
% You can sum and subtract row vectors only when they are the same size, i.e., speaking about polynomials, when the corresponding polynomials have the same degree.
% Thus, to sum (subtract) two polynomials with different degrees, you must insert leading zero elements in the row vector associated with the lowest degree polynomial, before starting with the algebraic operation.
% An Example:
% The algebraic operations
% p(x) = x^4-4\,x^3-x \;,\qquad q(x) = x^2-x-6 \quad \Longrightarrow \quad \begin{array}{rcl}
% p(x)+q(x) &=& ? \\
% p(x) - q(x) &=& ?
% \end{array}
% translate in the following lines of code

clear p q
p = [1  -4  0  -1  0];  % p(x) <--> a polynomial of 4th degree

q = [0   0  1  -1  -6]; % q(x) as a polynomial of 4th degree (indeed it is a 2nd degree polynomial!)

sum_p_q = p+q

subtract_p_q = p-q

% Of course:
% \begin{array}{l}
% p(x)+q(x) = x^4-4\,x^3+x^2-2\,x-6 \\
% p(x) - q(x) = x^4-4\,x^3-x^2 +6
% \end{array}
%
% Multiplying or Dividing Polynomials
% Given the polynomials
% p(x) = x^4-4\,x^3-x \;,\qquad q(x) = x^2-x-6
% determine the following polynomials
% \begin{array}{rcl}
% w(x) &:& w(x) = p(x) \cdot q(x) = \big(x^4-4\,x^3-x \big) \cdot \big(x^2-x-6 \big) = ? \\
% m(x),\, r(x) &:& q(x) \cdot m(x) + r(x) = p(x) \,,\; p(x) / q(x) = m(x) = ? \;,\quad r(x) = ?
% \end{array}
%
% Multiplying polynomials:
%  w = conv(p,q)
% returns the convolution of the vectors p and q. If p and q are vectors of polynomial coefficients, their convolution is equivalent to multiplying the two polynomials.

clear p q
p = [1  -4  0  -1  0];  % p(x) <--> a polynomial of 4th degree

q = [1  -1  -6]; % q(x) as a polynomial of 2nd degree 

w = conv(p, q) % Note: w must be a 6th degree polynomial, thus the corresponding row-vector contains 7 elements

% The resulting polynomial is indeed    w(x) = x^6-5\,x^5-2\,x^4+23\,x^3+x^2+6\,x
%
% Polynomial long division: Given the vectors of polynomial coefficients p and q,
% [m, r] = deconv(p, q)
% deconvolves the vector q out of the vector p using polynomial long division, and returns the quotient m and remainder r such that:   p = conv(q, m) + r

[m, r] = deconv(w, q)

% As expected, the quotient vector contains the coefficients of the polynomial p, whereas the reminder r is null.
% One more example:

clear m r
[m, r] = deconv(p, q)

% Thus:
% p(x) = q(x) \cdot m(x) + r(x) =\quad \Longleftrightarrow \quad x^4-4\,x^3-x = \big(x^2-x-6 \big) \cdot \big(x^2-3\,x+3 \big) + \big(-16\,x+18 \big)
%
%% Integrating and Differentiating Polynomials
%
% Integrating polynomials: simply apply the MATLAB command polyint.
%
% Let's start with an example involving the evaluation of an indefinite integral:
% p(x) = 3\,x^2 -2 \quad \Longrightarrow \quad q(x) = \int p(x)\,dx = x^3-2\,x+c\,,\; c \in \mathbb{R} \;,\quad c = q(0)

clear p q
p = [3 0 -2]; % coefficients of the polynomial p(x)

q0 = 4.815; % NB we cannot keep the integration constant "c" as symbolic element! We must assign a numeric value to it!
q = polyint(p, q0)

% In case we assign the null value to the integration constant c, then we may write simply

q1 = polyint(p)  % NB this time the integration constant c is null

% Note the last coefficient in the row-vector q1.
%
% What about the evaluation of the definite integral of a polynomial?
% I = \int_{-3}^{+4}  \big( x^4-4\,x^3-x \big)\,dx = \left(\frac{1}{5}\,x^5-x^4-\frac{1}{2}\,x^2 \right)\,\Big |_{-3}^{+4}

clear p q
p = [1  -4  0  -1  0];
q = polyint(p)
% let's assign the integration extrema
a = -3;
b = +4;

% Let's evaluate the integral:

Ival1 = polyval(q, b) - polyval(q, a)

IvalALT = diff(polyval(q, [a, b]))

%
% Differentiating polynomials
% Use polyder to obtain the derivative of a polynomial
% p(x) = \left(\frac{1}{5}\,x^5-x^4-\frac{1}{2}\,x^2\right) \quad \Longrightarrow \quad q(x) = \frac{d\,p(x)}{d\,x} = ?

clear p q
p = [1/5  -1  0  -1/2  0  0];
q = polyder(p)

% Thus
% q(x) = x^4-4\,x^3-x
%
%
% You can compute also the derivative of the product of two polynomials:
% p(x) = x^4-4\,x^3-x \;,\qquad q(x) = x^2-x-6 \quad \Longrightarrow \quad \frac{d\,}{d\,x} \big(p(x)\cdot q(x) \big) = ?

clear p q
p = [1  -4  0  -1  0];
q = [1  -1  -6];

% pay attention to the command syntax!
m = polyder(p, q) % <<<--- 2 inputs, only 1 output <-> derivative of the product p*q

%
% You can exploit the command polyder also to compute the derivative of a rational function
% q(x) = x^4-4\,x^3-x \;,\qquad p(x) = x^2-x-6 \quad \Longrightarrow \quad
%  \frac{d\,}{d\,x} \left[ \frac{p(x)}{q(x)} \right] = \frac{d\,}{d\,x} \left[ \frac{x^2-x-6}{x^4-4\,x^3-x} \right] = \frac{m(x)}{d(x)} = ?

clear p q
q = [1  -4  0  -1  0];
p = [1  -1  -6];

% pay attention to the command syntax!
[m, d] = polyder(p, q) % <<<--- 2 inputs, 2 outputs <-> derivative of the rational function p(x)/q(x)

% Thus
% \frac{d\,}{d\,x} \left[ \frac{x^2-x-6}{x^4-4\,x^3-x} \right] =
% \frac{-2x^5+7x^4+16x^3-73x^2 -6}{x^8-8x^7+16x^6-2x^5+8x^4+x^2}
%
%% Functions: The General Syntax
% MATLAB provides the ability to define your own functions:
% An M-file is a MATLAB function if and only if the first line of the file contains the following text
% function [output variable list] = function_name (input variable list)
% Terminating the file with a keyword is unnecessary: usually, a function ends when the last instruction line of the M-file describing it (which may be an "end" MATLAB keyword) is reached.
% You can force termination at any point using the 'return' instruction (see help return for details).
%% An Example
% Calculating the area of any triangle according to the formula
% \mathcal{A} = \displaystyle \sqrt{s\cdot \left(s-a\right)\cdot \left(s-b\right)\cdot \left(s-c\right)}\;,\quad s= \frac{a+b+c}{2}
% where a\,,\;b\,,\;c are the lengths of the triangle sides.
%
% The function then (in its simplest version) has 3 input parameters and only 1 output parameter:

edit evalTriangleArea

%
% Please note the initial comment lines in the M-file text. They are useful to implement the help contents for the custom MATLAB function.
% To see how the help command uses such helping lines, just run the following

help evalTriangleArea

%
% Using the custom function
% assigning an output variable

format short
Area = evalTriangleArea(10,15,20)

% without assigning the output variable

evalTriangleArea(10,15,20)

%
%% Functions Applied to a Vector
%
% Most MATLAB functions have been modified (overloaded) so they work with inputs which are vectors as well as scalars. When an argument is a vector the function is applied to each element of the vector, producing a vector of the same size as the input vector.
%% Examples

sqrt(1:10)

xv = -1:1/2:1 % a row vector with 5 elements
sin( (pi/2)*xv )

% Sometimes the result of the function has fewer elements than the input:

sum(xv)

max(xv)

%
%% Summary
%
% Using this live script you have:
% learned about MATLAB wide range of elementary mathematical functions;
% learned how to write an own custom MATLAB function;
% learned that many of MATLAB functions accept a vector as input, creating a vector as output, where the function has been evaluated at each element of the input vector.
%
%% Back to the Index
% Use this link to go back to the main live script of the collection.
%
%% Back to the Previous Part: Symbolic Math Computations
% Use this link to go back to the previous live script of this collection.
%
%% Go to the Next Part: LTI Systems
% Use this link to go to the next live script of the collection.
%
%
%
%