%% 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB
%%  Part  4 - Symbolic Math Computations
%%
% This is the fourth 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  4 - Symbolic Math Computations
%     Introduction
%     With a Little Help from the 'help' Command!
%         Before You Start
%     Symbolic Scalar Variables & Functions
%         Symbolic Scalar Variables
%             Assumptions on Symbolic Variables
%         Symbolic Functions
%             Example
%         Solving Symbolic Equations
%             How to Define a Symbolic Equation: A Few Examples
%             First Example
%             Second Example
%             Third Example
%             Fourth Example: Numerically Solve Equations
%     The Laplace Transform
%     Symbolic Vectors & Matrices
%             Examples: Using Already Existent Symbolic Variables
%             Examples: Creating Matrix of Symbolic Numbers
%         Linear Algebra with Symbolic Matrices
%     Summary
%             Back to the Index
%             Back to the Previous Part: Vectors and Matrices
%             Go to the Next Part: Visualization and Programming
%
%% Introduction
%
% Symbolic Math Toolbox provides functions for solving, representing and manipulating symbolic math equations. The toolbox offers functions for calculus, linear algebra, algebraic and differential equations, simplification and manipulation of equations. Symbolic Math Toolbox allows analytical derivations, integrations, simplifications, solving of equations, applying Laplace transform, and much more.
%% 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 symbolic calculation
% Symbolic Math Toolbox

help symbolic

%
%
%
%% Before You Start
% In this live script you will learn, by running some examples
% How to define and manage symbolic variables;
% How to perform linear algebraic operations, such as computing the inverse, or the determinant, or the eigenvalues of a square matrix;
% How to apply the Laplace transform.

clear  
close all
clc                 % cleaning the workspace
sympref('default')  % forcing the default preferences for the Symbolic Math Toolbox
old_prefs = sympref(); % store the actual Symbolic Toolbox preferences
sympref('MatrixWithSquareBrackets',true); % matrix style using [] 

% What are the symbolic Toolbox preferences? How to set it properly?

help sympref

%
%% Symbolic Scalar Variables & Functions
%
%% Symbolic Scalar Variables
% The command
% syms var1
% allows the definition of a scalar symbolic variable, named var1,  assigning to the new variable a symbolic value corresponding to the variable's name
% A simple example:

syms x y t
disp(x)
disp(y)
whos t

% Then, you may create a symbolic expression using the new variables, and assign the result to one of them

t = 2*y^2-sqrt(abs(x-pi))/sin(2*x-pi/6);
whos t
disp(t)

%
%% Assumptions on Symbolic Variables
% It is possible to declare assumptions on symbolic variables, regarding particular features or data type of the variables. The assumption can be 'real', 'rational', 'integer', or 'positive'.

syms a b integer
syms c positive rational
syms d real
disp(assumptions([a,b,c,d]))

% Alternatively, you may check assumptions on a single symbolic variable

syms a positive integer
disp(assumptions(a))

%
%% Symbolic Functions
% You may create symbolic scalar functions with one or two arguments, simply by typing, for example
% syms z(t) f(x, y)
% Both z and fare abstract symbolic functions. You have to assign an expression to them before using them.
%% Example

syms f(x, y)
f(x, y) = 2*x+sqrt(3*y^2+4)

% Now, it is possible to evaluate the function at a specific input point:

f(1,2)

%
%% Solving Symbolic Equations
%
% Is it possible to solve linear or nonlinear equations using the Symbolic Toolbox? Yes, it is: you can exploit the MATLAB command solve.

help symbolic/solve    

%%
%
%% How to Define a Symbolic Equation: A Few Examples
%
% Given the equations
% \begin{array}{clccl}
% \mathcal{E}_1: & a\, x^4+bx^2+c = 0 &\qquad &\mathcal{E}_2:& \frac{x}{2}+\frac{1}{x} = x \\
% \mathcal{E}_3: & \left\{ \begin{array}{rcl} 2x+y &=&0 \\ x-y &=& 1 \end{array} \right. & \qquad & \mathcal{E}_4: & x = \cos x
% \end{array}
%
% let's use the command solve to determine each solution, if possible.
%
%% First Example
% \mathcal{E}_1: \quad a\, x^4+bx^2+c = 0\;,\qquad x=?
% Let's define the symbolic variable x and the parameters a,\,b,\,c

syms x
syms a b c

% Define the equation as symbolic expression - note the particular syntax

Eq1 = a*x^4+b*x^2+c == 0

% Let's solve the equation, declaring explicitly that x si the variable, whereas a,\,b and c are the coefficients of the equation:

S1 = solve(Eq1, x)

%
%
%% Second Example
% \mathcal{E}_2: \quad \frac{x}{2}+\frac{1}{x} = x \;,\qquad x=?
% Let's define the symbolic variable x

clear a b c x
syms x

% Define the equation as symbolic expression

Eq2 = (x/2)+(1/x) == x

% Let's solve the equation

S2 = solve(Eq2)

%
%% Third Example
% \mathcal{E}_3: \quad  \left\{ \begin{array}{rcl} 2x+y &=&0 \\ x-y &=& 1 \end{array} \right.

clear x

syms x y

% Define the equation as a set of two symbolic expression (i..e. a column-vector, containing two equations)

Eq3 = [ 2*x+y ==0;
         x-y == 1 ]

% Let's solve the equations

S3 = solve(Eq3)

%
% If the solve function returns an empty object, then no solutions exist:
% \mathcal{E}_{3b}: \quad  \left\{ \begin{array}{rcl} 3x+2 &=&0 \\ 3x-1 &=& 0 \end{array} \right.

Eq3b = [ 3*x+2 == 0;
         3*x-1 == 0]
solve(Eq3b)

%
%% Fourth Example: Numerically Solve Equations
%
% When the solve function cannot symbolically solve an equation, it tries to find a numeric solution using the vpasolve function.
% Note: The vpasolve function returns the first solution found.
%
% \mathcal{E}_4: \qquad x = \cos x

clear x y
syms x
Eq4 = x == cos(x)

S4 = solve(Eq4)

%
%% The Laplace Transform
%
% The Laplace transform is a mapping of  a mathematical function from one domain (the time t) to another (the complex frequency s).
% Why use transforms?
% Some mathematical problems are difficult to solve in their natural domain.
% Transform to and solve in a new domain, where the problem is simplified.
% Solved the problem in the new domain, transform the solution back into the original domain.
% The Laplace transform converts integral and differential equations into algebraic equations (compare with the phasor method).
% A simple example:

syms t s % t and s are now symbolic variables
f = exp(-t) * cos(2 * t)
F = laplace(f, t, s)

% You can also calculate the inverse Laplace transform:

ft1 = ilaplace(F, s, t)

%
% For Laplace transform properties and how to use the Symbolic Math Toolbox to compute a Laplace transform or an inverse transform, refer to the live script Intro_MATLAB_034IN_FAC_p4L_1_LAPLACE.mlx .
%
% For application examples of the Laplace transform and how to use it in solving exercises in the 034IN course, refer to the live script Intro_MATLAB_034IN_FAC_p4L_2_LAPLACE_APPLIC.mlx .
%
%
%% Symbolic Vectors & Matrices
%
% The two most effective ways (during this course) to define a symbolic vector or a symbolic matrix are as follows:
% You may define a symbolic vector or matrix using already existent symbolic (scalar) variables.
% You may create a vector (or a matrix) of symbolic numbers.
%% Examples: Using Already Existent Symbolic Variables

clear variables % let's delete all the variables defined so far

syms a b c % let's define some scalar symbolic variables

A = [a b c; c a b; b c a]

% Note: the sum of the elements over each row and each column is the same

sum(A(:,1))

sum(A(2,:))

% Another example:

syms m1 m2 k1 k2 omega

M = [(-m1*omega^2 + k1)  (-k1);  (-k1)  (-m2*omega^2 + k1 + k2)]

% Let's evaluate the determinant of the M matrix, as an ordered polynomial of the symbolic variable \omega:

detM = collect(det(M), omega)

% We can also determine the symbolic values of \omega that are the root of the polynomial:

omegaSOL = solve(detM, omega)

%
%
%% Examples: Creating Matrix of Symbolic Numbers
% A particularly effective use of the command sym is to convert a matrix from numeric to symbolic form.
%
% For example, given the numeric matrix defined as

A = [1 1 0; 0 1 0; 0 0 1] % a numeric matrix

% we can obtain a symbolic representation of the same matrix simply by applying the command sym

Asym = sym(A)

% or equivalently

Asym2 = sym([1 1 0; 0 1 0; 0 0 1])

%
% For the complete syntax of the command sym, and some examples, refer to
% help sym
%
% or
% doc sym
%
%
%% Linear Algebra with Symbolic Matrices
%
% How to manage symbolic matrices, to compute the determinant or the inverse matrix of a symbolic matrix?
% How to implement and solve the linear algebra equation Ax = b using the Symbolic Math Toolbox?
% How to cope with the linear algebra equations' critical cases, when no solution or infinite solutions exist?
% The answers to these questions and some useful examples are available in the live script Part 4A-2 - Application: Solving Linear Algebra Equations.
%
%% Summary
%
% Using this live script you have:
% learned how  to define and manage symbolic variables;
% learned how  to perform linear algebraic operations, such as computing the inverse, or the determinant, or the eigenvalues of a square matrix;
% learned how to apply the Laplace transform.
%
%% Back to the Index
% Use this link to go back to the main live script of the collection.
%
%% Back to the Previous Part: Vectors and Matrices
% Use this link to go back to the previous live script of this collection.
%
%% Go to the Next Part: Visualization and Programming
% Use this link to go to the next live script of the collection.
%