Monday, March 17, 2014

MATLAB - Simulink

Simulink is a simulation and model-based design environment for dynamic and embedded systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modeling, simulating and analyzing multi-domain dynamic systems. It is basically a graphical block diagramming tool with customizable set of block libraries.
It allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis.
Simulink supports:
  • system-level design
  • simulation
  • automatic code generation
  • testing and verification of embedded systems
There are several other add-on products provided by MathWorks and third-party hardware and software products that are available for use with Simulink.
The following list gives brief description of some of them:
  • Stateflow allows developing state machines and flow charts.
  • Simulink Coder allows to automatically generate C source code for real-time implementation of systems.
  • xPC Target together with x86-based real-time systems provides an environment to simulate and test Simulink and Stateflow models in real-time on the physical system.
  • Embedded Coder supports specific embedded targets.
  • HDL Coder allows to automatically generate synthesizable VHDL and Verilog
  • SimEvents provides a library of graphical building blocks for modeling queuing systems
Simulink is capable of systematic verification and validation of models through modeling style checking, requirements traceability and model coverage analysis.
Simulink Design Verifier allows you identify design errors and generates test case scenarios for model checking.

Using Simulink

To open Simulink, type in the MATLAB work space:
simulink
Simulink opens with the Library Browser. The Library Browser is used for building simulation models.
 Simulink Library Browser On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane.

Building Models

To create a new model, click the New button on the Library Browser's toolbar. This opens a new untitled model window
Simulink New Model Window A Simulink model is a block diagram.
Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window.
Alternately, you can copy the model elements and paste them into the model window.

Examples

Drag and drop items from the Simulink library to make your project.
For the purpose of this example, 2 blocks will be used for the simulation - A Source (a signal) and a Sink (a scope). A signal generator (the source) generates an analog signal, which will then be graphically visualized by the scope(the sink).
Source and Sink Begin by dragging the required blocks from the library to the project window. Then, connect the blocks together which can be done by dragging connectors from connection points on one block to those of another.
Let us drag a 'Sine Wave' block into the model.
Sine Wave Block Select 'Sinks' from the library and drag a 'Scope' block into the model.
Scope Block Drag a signal line from the output of the Sine Wave block to the input of the Scope block.
Blocks are not connected Blocks are connected Run the simulation by pressing the 'Run' button, keeping all parameters default (you can change them from the Simulation menu)
You should get the below graph from the scope.
Simulation

MATLAB - GNU Octave Tutoirial

GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations.
Octave has the following common features with MATLAB:
  • matrices are fundamental data type
  • it has built-in support for complex numbers
  • it has built-in math functions and libraries
  • it supports user-defined functions
GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation.

MATLAB vs Octave

Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not.
For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave.

Compatible Examples

Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes:
This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code:
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
print -deps graph.eps
When you run the file, MATLAB displays the following 3-D map:
3-D Map in Matlab

Non-compatible Examples

Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax.
Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code:
f = x^2*cos(x);
ezplot(f, [-4,9])
a = int(f, -4, 9)
disp('Area: '), disp(double(a));
When you run the file, MATLAB plots the graph:
Definite Integral and displays the following result:
a =
 
8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)
 
Area: 
    0.3326
But to give area of the same curve in Octave, you will have to make use of symbolic package as follows:
pkg load symbolic
symbols

x = sym("x");

f = inline("x^2*cos(x)");

ezplot(f, [-4,9])
print -deps graph.eps

[a, ierror, nfneval] = quad(f, -4, 9);

display('Area: '), disp(double(a));

MATLAB - Transforms

MATLAB provides command for working with transforms, such as the Laplace and Fourier transforms. Transforms are used in science and engineering as a tool for simplifying analysis and look at data from another angle.
For example, the Fourier transform allows us to convert a signal represented as a function of time to a function of frequency. Laplace transform allows us to convert a differential equation to an algebraic equation.
MATLAB provides the laplace, fourier and fft commands to work with Laplace, Fourier and Fast Fourier transforms.

The Laplace Transform

The Laplace transform of a function of time f(t) is given by the following integral:
Laplace Transform Laplace transform is also denoted as transform of f(t) to F(s). You can see this transform or integration process converts f(t), a function of the symbolic variable t, into another function F(s), with another variable s.
Laplace transform turns differential equations into algebraic ones. To compute a Laplace transform of a function f(t), write:
laplace(f(t))

Example

In this example, we will compute the Laplace transform of some commonly used functions.
Create a script file and type the following code:
syms s t a b w
laplace(a)
laplace(t^2)
laplace(t^9)
laplace(exp(-b*t))
laplace(sin(w*t))
laplace(cos(w*t))
When you run the file, it displays the following result:
ans =
 1/s^2

 ans =
 2/s^3

 ans =
 362880/s^10

 ans =
 1/(b + s)
  
ans =
 w/(s^2 + w^2)
  
ans =
 s/(s^2 + w^2)

The Inverse Laplace Transform

MATLAB allows us to compute the inverse Laplace transform using the command ilaplace.
For example,
ilaplace(1/s^3)
MATLAB will execute the above statement and display the result:
ans =
 t^2/2

Example

Create a script file and type the following code:
syms s t a b w
ilaplace(1/s^7)
ilaplace(2/(w+s))
ilaplace(s/(s^2+4))
ilaplace(exp(-b*t))
ilaplace(w/(s^2 + w^2))
ilaplace(s/(s^2 + w^2))
When you run the file, it displays the following result:
ans =
t^6/720

 ans =
 2*exp(-t*w)

 ans =
 cos(2*t)

 ans =
 ilaplace(exp(-b*t), t, x)

 ans =
 sin(t*w)

 ans =
 cos(t*w)

The Fourier Transforms

Fourier transforms commonly transforms a mathematical function of time, f(t), into a new function, sometimes denoted by or F, whose argument is frequency with units of cycles/s (hertz) or radians per second. The new function is then known as the Fourier transform and/or the frequency spectrum of the function f.

Example

Create a script file and type the following code in it:
syms x 
f = exp(-2*x^2);  %our function
ezplot(f,[-2,2])  % plot of our function
FT = fourier(f) % Fourier transform
When you run the file, MATLAB plots the following graph:
Fourier Transforms And displays the following result:
FT =
 (2^(1/2)*pi^(1/2)*exp(-w^2/8))/2
Plotting the Fourier transform as:
ezplot(FT)
Gives the following graph:
Plotting the fourier transform

Inverse Fourier Transforms

MATLAB provides the ifourier command for computing the inverse Fourier transform of a function. For example,
f = ifourier(-2*exp(-abs(w)))
MATLAB will execute the above statement and display the result:
f =
-2/(pi*(x^2 + 1))

MATLAB - Polynomials

MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as:
p = [1 7 0 -5 9];

Evaluating Polynomials

The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type:
p = [1 7 0  -5 9];
polyval(p,4)
MATLAB executes the above statements and returns the following result:
ans =
   693
MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables.
For example, let us create a square matrix X and evaluate the polynomial p, at X:
p = [1 7 0  -5 9];
X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];
polyvalm(p, X)
MATLAB executes the above statements and returns the following result:
ans =
        2307       -1769        -939        4499
        2314       -2376        -249        4695
        2256       -1892        -549        4310
        4570       -4532       -1062        9269

Finding the Roots of Polynomials

The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type:
p = [1 7 0  -5 9];
r = roots(p)
MATLAB executes the above statements and returns the following result:
r =
  -6.8661 + 0.0000i
  -1.4247 + 0.0000i
   0.6454 + 0.7095i
   0.6454 - 0.7095i
The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example:
p2 = poly(r)
MATLAB executes the above statements and returns the following result:
p2 =
    1.0000    7.0000    0.0000   -5.0000    9.0000

Polynomial Curve Fitting

The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing:
p = polyfit(x,y,n)

Example

Create a script file and type the following code:
x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67];  %data
p = polyfit(x,y,4)   %get the polynomial
% Compute the values of the polyfit estimate over a finer range, 
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;          
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on
When you run the file, MATLAB displays the following result:
p =
    4.1056  -47.9607  222.2598 -362.7453  191.1250
And plots the following graph:
Polynomial Curve Fitting

MATLAB - Integration

Integration deals with two essentially different types of problems.
  • In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral.
  • The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral.
Definite integrals are used for finding area, volume, center of gravity, moment of inertia, work done by a force, and in numerous other applications.

Finding Indefinite Integral Using MATLAB

By definition, if the derivative of a function f(x) is f'(x), then we say that an indefinite integral of f'(x) with respect to x is f(x). For example, since the derivative (with respect to x) of x2 is 2x, we can say that an indefinite integral of 2x is x2.
In symbols:
f'(x2) = 2x, therefore,
∫ 2xdx = x2.
Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also be 2x.
This is expressed in symbols as:
∫ 2xdx = x2 + c.
Where, c is called an 'arbitrary constant'.
MATLAB provides an int command for calculating integral of an expression. To derive an expression for the indefinite integral of a function, we write:
int(f);
For example, from our previous example:
syms x 
int(2*x)
MATLAB executes the above statement and returns the following result:
ans =
 x^2

Example 1

In this example, let us find the integral of some commonly used expressions. Create a script file and type the following code in it:
syms x n
int(sym(x^n))
f = 'sin(n*t)'
int(sym(f))
syms a t
int(a*cos(pi*t))
int(a^x)
When you run the file, it displays the following result:
ans =
 piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])
f =
sin(n*t)
ans =
 -cos(n*t)/n
 ans =
 (a*sin(pi*t))/pi
 ans =
 a^x/log(a)

Example 2

Create a script file and type the following code in it:
syms x n
int(cos(x))
int(exp(x))
int(log(x))
int(x^-1)
int(x^5*cos(5*x))
pretty(int(x^5*cos(5*x)))
int(x^-5)
int(sec(x)^2)
pretty(int(1 - 10*x + 9 * x^2))
int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2)
pretty(int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2))
Note that the pretty command returns an expression in a more readable format.
When you run the file, it displays the following result:
ans =
 
sin(x)
 
 
ans =
 
exp(x)
 
 
ans =
 
x*(log(x) - 1)
 
 
ans =
 
log(x)
 
 
ans =
 
(24*cos(5*x))/3125 + (24*x*sin(5*x))/625 - (12*x^2*cos(5*x))/125 + (x^4*cos(5*x))/5 - (4*x^3*sin(5*x))/25 + (x^5*sin(5*x))/5
 
 
                                    2             4 
  24 cos(5 x)   24 x sin(5 x)   12 x  cos(5 x)   x  cos(5 x) 
  ----------- + ------------- - -------------- + ----------- - 
     3125            625             125              5 
   
        3             5 
 
    4 x  sin(5 x)   x  sin(5 x) 
     ------------- + ----------- 
          25              5
 
ans =
 
-1/(4*x^4)
 
 
ans =
 
tan(x)
 
 
        2 
  x (3 x  - 5 x + 1)
 
ans =
 
- (7*x^6)/12 - (3*x^5)/5 + (5*x^4)/8 + x^3/2
 
 
       6      5      4    3 
    7 x    3 x    5 x    x 
  - ---- - ---- + ---- + -- 
     12     5      8     2

Finding Definite Integral Using MATLAB

By definition, definite integral is basically the limit of a sum. We use definite integrals to find areas such as the area between a curve and the x-axis and the area between two curves. Definite integrals can also be used in other situations, where the quantity required can be expressed as the limit of a sum.
The int command can be used for definite integration by passing the limits over which you want to calculate the integral.
To calculate
Definite Integral we write,
int(x, a, b)
For example, to calculate the value of Example we write:
int(x, 4, 9)
MATLAB executes the above statement and returns the following result:
ans =
 65/2
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");

f = x;

c = [1, 0];
integral = polyint(c);

a = polyval(integral, 9) - polyval(integral, 4);

display('Area: '), disp(double(a));
An alternative solution can be given using quad() function provided by Octave as follows:
pkg load symbolic
symbols

f = inline("x");
[a, ierror, nfneval] = quad(f, 4, 9);

display('Area: '), disp(double(a));

Example 1

Let us calculate the area enclosed between the x-axis, and the curve y = x3−2x+5 and the ordinates x = 1 and x = 2.
The required area is given by:
Area Calculation Create a script file and type the following code:
f = x^3 - 2*x +5;
a = int(f, 1, 2)
display('Area: '), disp(double(a));
When you run the file, it displays the following result:
a =
23/4
Area: 
    5.7500
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");

f = x^3 - 2*x +5;

c = [1, 0, -2, 5];
integral = polyint(c);

a = polyval(integral, 2) - polyval(integral, 1);

display('Area: '), disp(double(a));
An alternative solution can be given using quad() function provided by Octave as follows:
pkg load symbolic
symbols

x = sym("x");

f = inline("x^3 - 2*x +5");

[a, ierror, nfneval] = quad(f, 1, 2);
display('Area: '), disp(double(a));

Example 2

Find the area under the curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9.
Create a script file and write the following code:
f = x^2*cos(x);
ezplot(f, [-4,9])
a = int(f, -4, 9)
disp('Area: '), disp(double(a));
When you run the file, MATLAB plots the graph:
Definite Integral and displays the following result:
a =
 
8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)
 
Area: 
    0.3326
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");

f = inline("x^2*cos(x)");

ezplot(f, [-4,9])
print -deps graph.eps

[a, ierror, nfneval] = quad(f, -4, 9);

display('Area: '), disp(double(a));

MATLAB - Differential

MATLAB provides the diff command for computing symbolic derivatives. In its simplest form, you pass the function you want to differentiate to diff command as an argument.
For example, let us compute the derivative of the function f(t) = 3t2 + 2t-2

Example

Create a script file and type the following code into it:
syms t
f = 3*t^2 + 2*t^(-2);
diff(f)
When the above code is compiled and executed, it produces the following result:
ans =
6*t - 4/t^3
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

t = sym("t");
f = 3*t^2 + 2*t^(-2);
differentiate(f,t)
Octave executes the code and returns the following result:
ans =

-(4.0)*t^(-3.0)+(6.0)*t

Verification of Elementary Rules of Differentiation

Let us briefly state various equations or rules for differentiation of functions and verify these rules. For this purpose, we will write f'(x) for a first order derivative and f"(x) for a second order derivative.
Following are the rules for differentiation:

Rule 1

For any functions f and g and any real numbers a and b the derivative of the function:
h(x) = af(x) + bg(x) with respect to x is given by:
h'(x) = af'(x) + bg'(x)

Rule 2

The sum and subtraction rules state that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f + g)' = f' + g'
(f - g)' = f' - g'

Rule 3

The product rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f.g)' = f'.g + g'.f

Rule 4

The quotient rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f/g)' = (f'.g - g'.f)/g2

Rule 5

The polynomial or elementary power rule states that, if y = f(x) = xn, then f' = n. x(n-1)
A direct outcome of this rule is derivative of any constant is zero, i.e., if y = k, any constant, then
f' = 0

Rule 6

The chain rule states that, The derivative of the function of a function h(x) = f(g(x)) with respect to x is,
h'(x)= f'(g(x)).g'(x)

Example

Create a script file and type the following code into it:
syms x
syms t
f = (x + 2)*(x^2 + 3)
der1 = diff(f)
f = (t^2 + 3)*(sqrt(t) + t^3)
der2 = diff(f)
f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)
der3 = diff(f)
f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = diff(f)
f = (x^2 + 1)^17
der5 = diff(f)
f = (t^3 + 3* t^2 + 5*t -9)^(-6)
der6 = diff(f)
When you run the file, MATLAB displays the following result:
f =
 (x^2 + 3)*(x + 2)
 
 der1 =
 2*x*(x + 2) + x^2 + 3
  
f =
 (t^(1/2) + t^3)*(t^2 + 3)
 
 der2 =
 (t^2 + 3)*(3*t^2 + 1/(2*t^(1/2))) + 2*t*(t^(1/2) + t^3)
  
f =
 (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)
  
der3 =
 (2*x - 2)*(3*x^3 - 5*x^2 + 2) - (- 9*x^2 + 10*x)*(x^2 - 2*x + 1)
 
 f =
 (2*x^2 + 3*x)/(x^3 + 1)
  
der4 =
 (4*x + 3)/(x^3 + 1) - (3*x^2*(2*x^2 + 3*x))/(x^3 + 1)^2
  
f =
 (x^2 + 1)^17
  
der5 =
 34*x*(x^2 + 1)^16
  
f =
1/(t^3 + 3*t^2 + 5*t - 9)^6
  
der6 =
 -(6*(3*t^2 + 6*t + 5))/(t^3 + 3*t^2 + 5*t - 9)^7
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols
x=sym("x");
t=sym("t");
f = (x + 2)*(x^2 + 3) 
der1 = differentiate(f,x) 
f = (t^2 + 3)*(t^(1/2) + t^3) 
der2 = differentiate(f,t) 
f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2) 
der3 = differentiate(f,x) 
f = (2*x^2 + 3*x)/(x^3 + 1) 
der4 = differentiate(f,x) 
f = (x^2 + 1)^17 
der5 = differentiate(f,x) 
f = (t^3 + 3* t^2 + 5*t -9)^(-6) 
der6 = differentiate(f,t)

Derivatives of Exponential, Logarithmic and Trigonometric Functions

The following table provides the derivatives of commonly used exponential, logarithmic and trigonometric functions:
FunctionDerivative
ca.xca.x.ln c.a (ln is natural logarithm)
exex
ln x1/x
lncx1/x.ln c
xxxx.(1 + ln x)
sin(x)cos(x)
cos(x)-sin(x)
tan(x)sec2(x), or 1/cos2(x), or 1 + tan2(x)
cot(x)-csc2(x), or -1/sin2(x), or -(1 + cot2(x))
sec(x)sec(x).tan(x)
csc(x)-csc(x).cot(x)

Example

Create a script file and type the following code into it:
syms x
y = exp(x)
diff(y)
y = x^9
diff(y)
y = sin(x)
diff(y)
y = tan(x)
diff(y)
y = cos(x)
diff(y)
y = log(x)
diff(y)
y = log10(x)
diff(y)
y = sin(x)^2
diff(y)
y = cos(3*x^2 + 2*x + 1)
diff(y)
y = exp(x)/sin(x)
diff(y)
When you run the file, MATLAB displays the following result:
y =
 exp(x)
 ans =
 exp(x)
 
 
y =
x^9
 ans =
 9*x^8
  
y =
 sin(x)
 ans =
 cos(x)
  
y =
 tan(x)
ans =
 tan(x)^2 + 1
 
 y =
 cos(x)
 ans =
 -sin(x)
  
y =
 log(x)
 ans =
 1/x
  
y =
 log(x)/log(10)
 ans =
 1/(x*log(10))
 
y =
 sin(x)^2
  ans =
 2*cos(x)*sin(x)
 
 y =
 
cos(3*x^2 + 2*x + 1)
 ans =
 -sin(3*x^2 + 2*x + 1)*(6*x + 2)
  
y =
 exp(x)/sin(x)
 ans =
 exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");
y = Exp(x)
differentiate(y,x)

y = x^9
differentiate(y,x)

y = Sin(x)
differentiate(y,x)

y = Tan(x)
differentiate(y,x)

y = Cos(x)
differentiate(y,x)

y = Log(x)
differentiate(y,x)

% symbolic packages does not have this support
%y = Log10(x)
%differentiate(y,x)

y = Sin(x)^2
differentiate(y,x)

y = Cos(3*x^2 + 2*x + 1)
differentiate(y,x)

y = Exp(x)/Sin(x)
differentiate(y,x)

Computing Higher Order Derivatives

To compute higher derivatives of a function f, we use the syntax diff(f,n).
Let us compute the second derivative of the function y = f(x) = x .e-3x
f = x*exp(-3*x);
diff(f, 2)
MATLAB executes the code and returns the following result:
ans =
9*x*exp(-3*x) - 6*exp(-3*x)
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");
f = x*Exp(-3*x);

differentiate(f, x, 2)

Example

In this example, let us solve a problem. Given that a function y = f(x) = 3 sin(x) + 7 cos(5x). We will have to find out whether the equation f" + f = -5cos(2x) holds true.
Create a script file and type the following code into it:
syms x
y = 3*sin(x)+7*cos(5*x);  % defining the function
lhs = diff(y,2)+y;        %evaluting the lhs of the equation
rhs = -5*cos(2*x);        %rhs of the equation
if(isequal(lhs,rhs))
    disp('Yes, the equation holds true');
else
    disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);
When you run the file, it displays the following result:
No, the equation does not hold true
Value of LHS is: 
-168*cos(5*x)
Following is Octave equivalent of the above calculation:
pkg load symbolic
symbols

x = sym("x");
y = 3*Sin(x)+7*Cos(5*x);           % defining the function
lhs = differentiate(y, x, 2) + y;  %evaluting the lhs of the equation
rhs = -5*Cos(2*x);                 %rhs of the equation

if(lhs == rhs)
    disp('Yes, the equation holds true');
else
    disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);

Finding the Maxima and Minima of a Curve

If we are searching for the local maxima and minima for a graph, we are basically looking for the highest or lowest points on the graph of the function at a particular locality, or for a particular range of values of the symbolic variable.
For a function y = f(x) the points on the graph where the graph has zero slope are called stationary points. In other words stationary points are where f'(x) = 0.
To find the stationary points of a function we differentiate, we need to set the derivative equal to zero and solve the equation.

Example

Let us find the stationary points of the function f(x) = 2x3 + 3x2 − 12x + 17
Take the following steps:
  1. First let us enter the function and plot its graph:
    syms x
    y = 2*x^3 + 3*x^2 - 12*x + 17;  % defining the function
    ezplot(y)
    MATLAB executes the code and returns the following plot:
    Finding Maxima and Minima Here is Octave equivalent code for the above example:
    pkg load symbolic
    symbols
    
    x = sym('x');
    y = inline("2*x^3 + 3*x^2 - 12*x + 17");
    
    ezplot(y)
    print -deps graph.eps
  2. Our aim is to find some local maxima and minima on the graph, so let us find the local maxima and minima for the interval [-2, 2] on the graph.
    syms x
    y = 2*x^3 + 3*x^2 - 12*x + 17;  % defining the function
    ezplot(y, [-2, 2])
    MATLAB executes the code and returns the following plot:
    Finding Maxima and Minima Here is Octave equivalent code for the above example:
    pkg load symbolic
    symbols
    
    x = sym('x');
    y = inline("2*x^3 + 3*x^2 - 12*x + 17");
    
    ezplot(y, [-2, 2])
    print -deps graph.eps
  3. Next, let us compute the derivative
    g = diff(y)
    MATLAB executes the code and returns the following result:
    g =
    6*x^2 + 6*x - 12
    
    Here is Octave equivalent of the above calculation:
    pkg load symbolic
    symbols
    
    x = sym("x");
    
    y = 2*x^3 + 3*x^2 - 12*x + 17;
    g = differentiate(y,x)
  4. Let us solve the derivative function, g, to get the values where it becomes zero.
    s = solve(g)
    MATLAB executes the code and returns the following result:
    s = 
       1
      -2
    
    Following is Octave equivalent of the above calculation:
    pkg load symbolic
    symbols
    
    x = sym("x");
    
    y = 2*x^3 + 3*x^2 - 12*x + 17;
    g = differentiate(y,x)
    roots([6, 6, -12])
  5. This agrees with our plot. So let us evaluate the function f at the critical points x = 1, -2. We can substitute a value in a symbolic function by using the subs command.
    subs(y, 1), subs(y, -2)
    MATLAB executes the code and returns the following result:
    ans =
     10
    ans =
     37
    
    Following is Octave equivalent of the above calculation:
    pkg load symbolic
    symbols
    
    x = sym("x");
    
    y = 2*x^3 + 3*x^2 - 12*x + 17;
    g = differentiate(y,x)
    
    roots([6, 6, -12])
    
    subs(y, x, 1), subs(y, x, -2)
    Therefore, The minimum and maximum values on the function f(x) = 2x3 + 3x2 − 12x + 17, in the interval [-2,2] are 10 and 37.

Solving Differential Equations

MATLAB provides the dsolve command for solving differential equations symbolically.
The most basic form of the dsolve command for finding the solution to a single equation is :
dsolve('eqn') 
where eqn is a text string used to enter the equation.
It returns a symbolic solution with a set of arbitrary constants that MATLAB labels C1, C2, and so on.
You can also specify initial and boundary conditions for the problem, as comma-delimited list following the equation as:
dsolve('eqn','cond1', 'cond2',…)  
For the purpose of using dsolve command, derivatives are indicated with a D. For example, an equation like f'(t) = -2*f + cost(t) is entered as:
'Df = -2*f + cos(t)'
Higher derivatives are indicated by following D by the order of the derivative.
For example the equation f"(x) + 2f'(x) = 5sin3x should be entered as:
'D2y + 2Dy = 5*sin(3*x)'
Let us take up a simple example of a first order differential equation: y' = 5y.
s = dsolve('Dy = 5*y')
MATLAB executes the code and returns the following result:
s =
 C2*exp(5*t)
Let us take up another example of a second order differential equation as: y" - y = 0, y(0) = -1, y'(0) = 2.
dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')
MATLAB executes the code and returns the following result:
ans =
 exp(t)/2 - (3*exp(-t))/2

MATLAB - Calculus

MATLAB provides various ways for solving problems of differential and integral calculus, solving differential equations of any degree and calculation of limits. Best of all, you can easily plot the graphs of complex functions and check maxima, minima and other stationery points on a graph by solving the original function, as well as its derivative.
In this chapter and in coming couple of chapters, we will deal with the problems of calculus. In this chapter, we will discuss pre-calculus concepts i.e., calculating limits of functions and verifying the properties of limits.
In the next chapter Differential, we will compute derivative of an expression and find the local maxima and minima on a graph. We will also discuss solving differential equations.
Finally, in the Integration chapter, we will discuss integral calculus.

Calculating Limits

MATLAB provides the limit command for calculating limits. In its most basic form, the limit command takes expression as an argument and finds the limit of the expression as the independent variable goes to zero.
For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends to zero.
syms x
limit((x^3 + 5)/(x^4 + 7))
MATLAB will execute the above statement and return the following result:
ans =
 5/7
The limit command falls in the realm of symbolic computing; you need to use the syms command to tell MATLAB which symbolic variables you are using. You can also compute limit of a function, as the variable tends to some number other than zero. To calculate lim x->a(f(x)), we use the limit command with arguments. The first being the expression and the second is the number, that x approaches, here it is a.
For example, let us calculate limit of a function f(x) = (x-3)/(x-1), as x tends to 1.
limit((x - 3)/(x-1),1)
MATLAB will execute the above statement and return the following result:
ans =
 NaN
Let's take another example,
limit(x^2 + 5, 3)
MATLAB will execute the above statement and return the following result:
ans =
 14

Calculating Limits using Octave

Following is Octave version of the above example using symbolic package, try to execute and compare the result:
pkg load symbolic
symbols
x=sym("x");

subs((x^3+5)/(x^4+7),x,0)
Octave will execute the above statement and return the following result:
ans =
0.7142857142857142857

Verification of Basic Properties of Limits

Algebraic Limit Theorem provides some basic properties of limits. These are as follows:
Basic Properties of Limits Let us consider two functions:
  1. f(x) = (3x + 5)/(x - 3)
  2. g(x) = x2 + 1.
Let us calculate the limits of the functions as x tends to 5, of both functions and verify the basic properties of limits using these two functions and MATLAB.

Example

Create a script file and type the following code into it:
syms x
f = (3*x + 5)/(x-3);
g = x^2 + 1;
l1 = limit(f, 4)
l2 = limit (g, 4)
lAdd = limit(f + g, 4)
lSub = limit(f - g, 4)
lMult = limit(f*g, 4)
lDiv = limit (f/g, 4)
When you run the file, it displays:
l1 =
 17
  
l2 =
17
  
lAdd =
 34
 
lSub =
 0
  
lMult =
289
  
lDiv =
1

Verification of Basic Properties of Limits using Octave

Following is Octave version of the above example using symbolic package, try to execute and compare the result:
pkg load symbolic
symbols

x = sym("x");
f = (3*x + 5)/(x-3);
g = x^2 + 1;

l1=subs(f, x, 4)
l2 = subs (g, x, 4)
lAdd = subs (f+g, x, 4)
lSub = subs (f-g, x, 4)
lMult = subs (f*g, x, 4)
lDiv = subs (f/g, x, 4)
Octave will execute the above statement and return the following result:
l1 =

17.0
l2 =

17.0
lAdd =

34.0
lSub =

0.0
lMult =

289.0
lDiv =

1.0

Left and Right Sided Limits

When a function has a discontinuity for some particular value of the variable, the limit does not exist at that point. In other words, limits of a function f(x) has discontinuity at x = a, when the value of limit, as x approaches x from left side, does not equal the value of the limit as x approaches from right side.
This leads to the concept of left-handed and right-handed limits. A left-handed limit is defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a, for values of x > a. When the left-handed limit and right-handed limits are not equal, the limit does not exist.
Let us consider a function:
f(x) = (x - 3)/|x - 3|
We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact in two ways:
  • By plotting the graph of the function and showing the discontinuity
  • By computing the limits and showing that both are different.
The left-handed and right-handed limits are computed by passing the character strings 'left' and 'right' to the limit command as the last argument.

Example

Create a script file and type the following code into it:
f = (x - 3)/abs(x-3);
ezplot(f,[-1,5])
l = limit(f,x,3,'left')
r = limit(f,x,3,'right')
When you run the file, MATLAB draws the following plot,
Discontinuity in a Function and displays the following output:
l =
 -1
  
r =
1