MATLAB Quick Guide
MATLAB Quick Guide
MATLAB - Overview
MATLAB (matrix laboratory) is a fourth-generation high-level programming language
and interactive environment for numerical computation, visualization and programming.
It has numerous built-in commands and math functions that help you in mathematical
calculations, generating plots, and performing numerical methods.
Linear Algebra
Algebraic Equations
Non-linear Functions
Statistics
Data Analysis
Numerical Calculations
Integration
Transforms
Curve Fitting
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 1/126
7/18/2019 MATLAB Quick Guide
Features of MATLAB
Following are the basic features of MATLAB −
It provides built-in graphics for visualizing data and tools for creating custom
plots.
Uses of MATLAB
MATLAB is widely used as a computational tool in science and engineering
encompassing the fields of physics, chemistry, math and all engineering streams. It is
used in a range of applications including −
Control Systems
Computational Finance
Computational Biology
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 2/126
7/18/2019 MATLAB Quick Guide
MathWorks provides the licensed product, a trial version and a student version as well.
You need to log into the site and wait a little for their approval.
After downloading the installer the software can be installed through few clicks.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 3/126
7/18/2019 MATLAB Quick Guide
Current Folder − This panel allows you to access the project folders and files.
Command Window − This is the main area where commands can be entered
at the command line. It is indicated by the command prompt (>>).
Workspace − The workspace shows all the variables created and/or imported
from files.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 4/126
7/18/2019 MATLAB Quick Guide
Command History − This panel shows or return commands that are entered at
the command line.
Hands on Practice
Type a valid expression, for example,
Live Demo
5 + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 5/126
7/18/2019 MATLAB Quick Guide
ans = 10
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
ans = 9
Another example,
Live Demo
sin(pi /2) % sine of angle 90o
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
ans = 1
Another example,
Live Demo
7/0 % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
ans = Inf
warning: division by zero
Another example,
Live Demo
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for
π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.
For example,
Live Demo
x = 3;
y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately
and the result returned is −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 6/126
7/18/2019 MATLAB Quick Guide
y = 8
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
You can also write a block of comments using the block comment operators % { and %
}.
The MATLAB editor includes tools and context menu items to help you add, remove, or
change the format of comments.
Operator Purpose
\ Left-division operator.
/ Right-division operator.
. Decimal point.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 7/126
7/18/2019 MATLAB Quick Guide
= Assignment operator.
Name Meaning
Inf Infinity.
pi The number π
Naming Variables
Variable names consist of a letter followed by any number of letters, digits or
underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters,
where N is given by the function namelengthmax.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
MATLAB - Variables
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 8/126
7/18/2019 MATLAB Quick Guide
MATLAB will execute the above statement and return the following result −
x = 3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check
another example,
Live Demo
x = sqrt(16) % defining x and initializing it with an expression
MATLAB will execute the above statement and return the following result −
x = 4
Once a variable is entered into the system, you can refer to it later.
When an expression returns a result that is not assigned to any variable, the
system assigns it to a variable named ans, which can be used later.
For example,
Live Demo
sqrt(78)
MATLAB will execute the above statement and return the following result −
ans = 8.8318
MATLAB will execute the above statement and return the following result −
ans = 1118.2
MATLAB will execute the above statement and return the following result −
y = 441.84
Multiple Assignments
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 9/126
7/18/2019 MATLAB Quick Guide
You can have multiple assignments on the same line. For example,
Live Demo
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14
who
MATLAB will execute the above statement and return the following result −
whos
MATLAB will execute the above statement and return the following result −
The clear command deletes all (or the specified) variable(s) from the memory.
Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For
example,
Live Demo
initial_velocity = 0;
acceleration = 9.8;
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 10/126
7/18/2019 MATLAB Quick Guide
time = 20;
final_velocity = initial_velocity + acceleration * time
MATLAB will execute the above statement and return the following result −
final_velocity = 196
However, if you want more precision, you need to use the format command.
For example −
Live Demo
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result−
x = 17.2319816406394
Another example,
Live Demo
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result −
x = 17.232
The format bank command rounds numbers to two decimal places. For example,
Live Demo
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result −
weekly_wage = 1064.70
The format short e command allows displaying in exponential form with four decimal
places plus the exponent.
For example,
Live Demo
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 2.2922e+01
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 11/126
7/18/2019 MATLAB Quick Guide
The format long e command allows displaying in exponential form with four decimal
places plus the exponent. For example,
Live Demo
format long e
x = pi
MATLAB will execute the above statement and return the following result −
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a
calculation. For example,
Live Demo
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 34177/1491
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of
vectors −
Row vectors
Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.
For example,
Live Demo
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
Another example,
Live Demo
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result −
res =
9 11 13 15 17
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 12/126
7/18/2019 MATLAB Quick Guide
Column vectors are created by enclosing the set of elements in square brackets, using
semicolon(;) to delimit the elements.
Live Demo
c = [7; 8; 9; 10; 11]
MATLAB will execute the above statement and return the following result −
c =
7
8
9
10
11
Creating Matrices
A matrix is a two-dimensional array of numbers.
MATLAB will execute the above statement and return the following result −
m =
1 2 3
4 5 6
7 8 9
MATLAB - Commands
MATLAB is an interactive program for numerical computation and data visualization. You
can enter a command by typing it at the MATLAB prompt '>>' on the Command
Window.
In this section, we will provide lists of commonly used general MATLAB commands.
Command Purpose
It also provides various commands for other system-related activities like, displaying
date, listing files in the directory, displaying current directory, etc.
Command Purpose
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 14/126
7/18/2019 MATLAB Quick Guide
Command Purpose
The fscanf and fprintf commands behave like C scanf and printf functions. They
support the following format codes −
%s Format as a string.
%d Format as an integer.
The format function has the following forms used for numeric display −
Command Purpose
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 16/126
7/18/2019 MATLAB Quick Guide
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows
some of the commonly used commands for plotting −
Command Purpose
MATLAB - M-Files
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a
powerful programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB
command prompt. MATLAB also allows you to write series of commands into a file and
execute the file as complete unit, like writing a function and calling it.
The M Files
MATLAB allows writing two kinds of program files −
Scripts − script files are program files with .m extension. In these files, you
write series of commands, which you want to execute together. Scripts do not
accept inputs and do not return any outputs. They operate on data in the
workspace.
You can use the MATLAB editor or any other text editor to create your .mfiles. In this
section, we will discuss the script files. A script file contains multiple sequential lines of
MATLAB commands and function calls. You can run a script by typing its name at the
command line.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 18/126
7/18/2019 MATLAB Quick Guide
If you are using the command prompt, type edit in the command prompt. This will
open the editor. You can directly type edit and then the filename (with .m extension)
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you want to
store all program files in a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command
prompt (>>) −
If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor
and creates a file named Untitled. You can name and save the file after typing the code.
After creating and saving the file, you can run it in two ways −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 19/126
7/18/2019 MATLAB Quick Guide
Just typing the filename (without extension) in the command prompt: >> prog1
6170
Example
Create a script file, and type the following code −
Live Demo
a = 5; b = 7;
c = a + b
d = c + sin(b)
e = 5 * d
f = exp(-d)
When the above code is compiled and executed, it produces the following result −
c = 12
d = 12.657
e = 63.285
f = 3.1852e-06
If the variable already exists, then MATLAB replaces the original content with new
content and allocates new storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in
it.
The following table shows the most commonly used data types in MATLAB −
int8
1
8-bit signed integer
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 20/126
7/18/2019 MATLAB Quick Guide
2 uint8
int16
3
16-bit signed integer
uint16
4
16-bit unsigned integer
int32
5
32-bit signed integer
uint32
6
32-bit unsigned integer
int64
7
64-bit signed integer
uint64
8
64-bit unsigned integer
single
9
single precision numerical data
double
10
double precision numerical data
logical
11
logical values of 1 or 0, represent true and false respectively
char
12
character data (strings are stored as vector of characters)
cell array
14 structure
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 21/126
7/18/2019 MATLAB Quick Guide
function handle
15
pointer to a function
user classes
16
objects constructed from a user-defined class
java classes
17
objects constructed from a Java class
Example
Create a script file with the following code −
Live Demo
str = 'Hello World!'
n = 2345
d = double(n)
un = uint32(789.50)
rn = 5678.92347
c = int32(rn)
When the above code is compiled and executed, it produces the following result −
Function Purpose
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 22/126
7/18/2019 MATLAB Quick Guide
mat2cell Convert array to cell array with potentially different sized cells
Following table provides the functions for determining the data type of a variable −
Function Purpose
is Detect state
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 23/126
7/18/2019 MATLAB Quick Guide
Example
Create a script file with the following code −
Live Demo
x = 3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 24/126
7/18/2019 MATLAB Quick Guide
isscalar(x)
isnumeric(x)
x = 3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x =
1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
MATLAB - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. MATLAB is designed to operate primarily on whole matrices and
arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data.
MATLAB allows the following types of elementary operations −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
Arithmetic Operators
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 25/126
7/18/2019 MATLAB Quick Guide
Matrix arithmetic operations are same as defined in linear algebra. Array operations are
executed element by element, both on one-dimensional and multidimensional array.
The matrix operators and array operators are differentiated by the period (.) symbol.
However, as the addition and subtraction operation is same for matrices and arrays, the
operator is same for both cases. The following table gives brief description of the
operators −
Show Examples
Addition or unary plus. A+B adds the values stored in variables A and B. A
1
and B must have the same size, unless one is a scalar. A scalar can be added
to a matrix of any size.
.*
5 Slash or matrix right division. B/A is roughly the same as B*inv(A). More
precisely, B/A = (A'\B')'.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 26/126
7/18/2019 MATLAB Quick Guide
6 ./
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B
must have the same size, unless one of them is a scalar.
.\
8 Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B
must have the same size, unless one of them is a scalar.
.^
10 Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A
and B must have the same size, unless one of them is a scalar.
'
.'
12 Array transpose. A.' is the array transpose of A. For complex matrices, this
does not involve conjugation.
Relational Operators
Relational operators can also work on both scalar and non-scalar data. Relational
operators for arrays perform element-by-element comparisons between two arrays and
return a logical array of the same size, with elements set to logical 1 (true) where the
relation is true and elements set to logical 0 (false) where it is not.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 27/126
7/18/2019 MATLAB Quick Guide
Show Examples
<
1
Less than
<=
2
Less than or equal to
>
3
Greater than
>=
4
Greater than or equal to
==
5
Equal to
~=
6
Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions −
Show Examples
Bitwise Operations
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 28/126
7/18/2019 MATLAB Quick Guide
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &,
|, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or'
and 'bitwise not' operations, shift operation, etc.
Show Examples
Function Purpose
Set Operations
MATLAB provides various functions for set operations, like union, intersection and
testing for set membership, etc.
Show Examples
intersect(A,B)
1 Set intersection of two arrays; returns the values common to both A and B.
The values returned are in sorted order.
intersect(A,B,'rows')
Treats each row of A and each row of B as single entities and returns the
2
rows common to both A and B. The rows of the returned matrix are in sorted
order.
ismember(A,B)
3 Returns an array the same size as A, containing 1 (true) where the elements
of A are found in B. Elsewhere, it returns 0 (false).
ismember(A,B,'rows')
Treats each row of A and each row of B as single entities and returns a
4
vector containing 1 (true) where the rows of matrix A are also rows of B.
Elsewhere, it returns 0 (false).
issorted(A)
Returns logical 1 (true) if the elements of A are in sorted order and logical 0
5 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array
of strings. A is considered to be sorted if A and the output of sort(A) are
equal.
issorted(A, 'rows')
7 setdiff(A,B)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 30/126
7/18/2019 MATLAB Quick Guide
Sets difference of two arrays; returns the values in A that are not in B. The
values in the returned array are in sorted order.
setdiff(A,B,'rows')
Treats each row of A and each row of B as single entities and returns the
8 rows from A that are not in B. The rows of the returned matrix are in sorted
order.
setxor
9
Sets exclusive OR of two arrays
union
10
Sets union of two arrays
unique
11
Unique values in array
Following is the general form of a typical decision making structure found in most of the
programming languages −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 31/126
7/18/2019 MATLAB Quick Guide
MATLAB provides following types of decision making statements. Click the following
links to check their detail −
if...else...end statement
2 An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
nested if statements
4 You can use one if or elseif statement inside another if or elseif
statement(s).
switch statement
5 A switch statement allows a variable to be tested for equality against a list
of values.
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially. The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
MATLAB provides following types of loops to handle looping requirements. Click the
following links to check their detail −
while loop
1 Repeats a statement or group of statements while a given condition is true.
It tests the condition before executing the loop body.
for loop
2 Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
nested loops
3 You can use one or more loops inside any another loop.
MATLAB supports the following control statements. Click the following links to check
their detail.
break statement
1 Terminates the loop statement and transfers execution to the statement
immediately following the loop.
continue statement
2 Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
MATLAB - Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of
vectors −
Row vectors
Column vectors
Row Vectors
Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.
Live Demo
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
Column Vectors
Column vectors are created by enclosing the set of elements in square brackets, using
semicolon to delimit the elements.
Live Demo
c = [7; 8; 9; 10; 11]
MATLAB will execute the above statement and return the following result −
c =
7
8
9
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 34/126
7/18/2019 MATLAB Quick Guide
10
11
MATLAB will execute the above statement and return the following result −
ans = 3
When you reference a vector with a colon, such as v(:), all the components of the
vector are listed.
Live Demo
v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements
v(:)
MATLAB will execute the above statement and return the following result −
ans =
1
2
3
4
5
6
For example, let us create a row vector rv of 9 elements, then we will reference the
elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv.
Live Demo
rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)
MATLAB will execute the above statement and return the following result −
sub_rv =
3 4 5 6 7
Vector Operations
In this section, let us discuss the following vector operations −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 35/126
7/18/2019 MATLAB Quick Guide
Transpose of a Vector
Appending Vectors
Magnitude of a Vector
MATLAB - Matrix
A matrix is a two-dimensional array of numbers.
In MATLAB, you create a matrix by entering elements in each row as comma or space
delimited numbers and using semicolons to mark the end of each row.
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
mx(m, n);
For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as
created in the last section, we type −
Live Demo
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(2,5)
MATLAB will execute the above statement and return the following result −
ans = 6
Let us create a column vector v, from the elements of the 4th row of the matrix a −
Live Demo
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
v = a(:,4)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 36/126
7/18/2019 MATLAB Quick Guide
MATLAB will execute the above statement and return the following result −
v =
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write −
a(:,m:n)
Let us create a smaller matrix taking the elements from the second and third columns
−
Live Demo
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
Live Demo
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
3 4 5
4 5 6
To do this, write −
Live Demo
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
sa = a(2:3,2:4)
MATLAB will execute the above statement and return the following result −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 37/126
7/18/2019 MATLAB Quick Guide
sa =
3 4 5
4 5 6
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Example
In this example, let us create a 3-by-3 matrix m, then we will copy the second and third
rows of this matrix twice to create a 4-by-3 matrix.
new_mat =
4 5 6
7 8 9
4 5 6
7 8 9
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 38/126
7/18/2019 MATLAB Quick Guide
Matrix Operations
In this section, let us discuss the following basic and commonly used matrix operations
−
Division of Matrices
Transpose of a Matrix
Concatenating Matrices
Matrix Multiplication
Determinant of a Matrix
Inverse of a Matrix
MATLAB - Arrays
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-
dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss
multidimensional arrays. However, before that, let us discuss some special types of
arrays.
For example −
Live Demo
zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
For example −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 39/126
7/18/2019 MATLAB Quick Guide
MATLAB will execute the above statement and return the following result −
ans =
1 1 1
1 1 1
1 1 1
1 1 1
For example −
Live Demo
eye(4)
MATLAB will execute the above statement and return the following result −
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1)
−
For example −
Live Demo
rand(3, 5)
MATLAB will execute the above statement and return the following result −
ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
A Magic Square
A magic square is a square that produces the same sum, when its elements are added
row-wise, column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that
gives the size of the square. The argument must be a scalar greater than or equal to 3.
Live Demo
magic(4)
MATLAB will execute the above statement and return the following result −
ans =
16 2 3 13
5 11 10 8
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 40/126
7/18/2019 MATLAB Quick Guide
9 7 6 12
4 14 15 1
Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array in
MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-
dimensional matrix.
MATLAB will execute the above statement and return the following result −
a =
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the
values like −
Live Demo
a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
a =
ans(:,:,1) =
0 0 0
0 0 0
0 0 0
ans(:,:,2) =
1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the rand()
functions.
For example,
Live Demo
b = rand(4,3,2)
MATLAB will execute the above statement and return the following result −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 41/126
7/18/2019 MATLAB Quick Guide
b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760
b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a
list of arrays along a specified dimension −
Where,
Example
Create a script file and type the following code into it −
Live Demo
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
Array Functions
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 42/126
7/18/2019 MATLAB Quick Guide
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift
array contents.
Function Purpose
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 43/126
7/18/2019 MATLAB Quick Guide
transpose Transpose
Examples
The following examples illustrate some of the functions mentioned above.
ans = 8
ans = 4
ans = 23
a =
1 2 3
4 5 6
7 8 9
b =
7 8 9
1 2 3
4 5 6
c =
8 9 7
2 3 1
5 6 4
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 44/126
7/18/2019 MATLAB Quick Guide
Sorting Arrays
Create a script file and type the following code into it −
Live Demo
v = [ 23 45 12 9 5 0 19 17] % horizontal vector
sort(v) % sorting v
m = [2 6 4; 5 3 9; 2 0 1] % two dimensional array
sort(m, 1) % sorting m along the row
sort(m, 2) % sorting m along the column
v =
23 45 12 9 5 0 19 17
ans =
0 5 9 12 17 19 23 45
m =
2 6 4
5 3 9
2 0 1
ans =
2 0 1
2 3 4
5 6 9
ans =
2 4 6
3 5 9
0 1 2
Cell Array
Cell arrays are arrays of indexed cells where each cell can store an array of a different
dimensions and data types.
The cell function is used for creating a cell array. Syntax for the cell function is −
C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)
Where,
dim is a scalar integer or vector of integers that specifies the dimensions of cell
array C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
Example
Create a script file and type the following code into it −
Live Demo
c = cell(2, 5);
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}
c =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
[1,3] = Green
[2,3] = 3
[1,4] = Yellow
[2,4] = 4
[1,5] = White
[2,5] = 5
}
Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.
For example −
Live Demo
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};
c(1:2,1:2)
MATLAB will execute the above statement and return the following result −
ans =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
}
You can also access the contents of cells by indexing with curly braces.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 46/126
7/18/2019 MATLAB Quick Guide
For example −
Live Demo
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};
c{1, 2:4}
MATLAB will execute the above statement and return the following result −
ans = Blue
ans = Green
ans = Yellow
If you want to create a row vector, containing integers from 1 to 10, you write −
Live Demo
1:10
MATLAB executes the statement and returns a row vector containing the integers from
1 to 10 −
ans =
1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example −
Live Demo
100: -5: 50
ans =
100 95 90 85 80 75 70 65 60 55 50
ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows, columns or
elements of arrays.
The following table describes its use for this purpose (let us have a matrix A) −
Format Purpose
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 47/126
7/18/2019 MATLAB Quick Guide
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
Example
Create a script file and type the following code in it −
Live Demo
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
A =
1 2 3 4
4 5 6 7
7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9
MATLAB - Numbers
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 48/126
7/18/2019 MATLAB Quick Guide
MATLAB supports various numeric classes that include signed and unsigned integers
and single-precision and double-precision floating-point numbers. By default, MATLAB
stores all numeric values as double-precision floating point numbers.
You can choose to store any number or array of numbers as integers or as single-
precision numbers.
All numeric types support basic array operations and mathematical operations.
Function Purpose
Example
Create a script file and type the following code −
Live Demo
x = single([5.32 3.47 6.28]) .* 7.5
x = double([5.32 3.47 6.28]) .* 7.5
x = int8([5.32 3.47 6.28]) .* 7.5
x = int16([5.32 3.47 6.28]) .* 7.5
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
x =
x =
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 49/126
7/18/2019 MATLAB Quick Guide
x =
38 23 45
x =
38 23 45
x =
38 23 45
x =
38 23 45
Example
Let us extend the previous example a little more. Create a script file and type the
following code −
Live Demo
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
x = num2cell(x)
x =
38 23 45
x =
38 23 45
x =
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 50/126
7/18/2019 MATLAB Quick Guide
Both the functions take the integer data type as the argument, for example,
intmax(int8) or intmin(int64) and return the maximum and minimum values that you
can represent with the integer data type.
Example
The following example illustrates how to obtain the smallest and largest values of
integers. Create a script file and write the following code in it −
Live Demo
% displaying the smallest and largest signed integer data
str = 'The range for int8 is:\n\t%d to %d ';
sprintf(str, intmin('int8'), intmax('int8'))
str = 'The range for int16 is:\n\t%d to %d ';
sprintf(str, intmin('int16'), intmax('int16'))
str = 'The range for int32 is:\n\t%d to %d ';
sprintf(str, intmin('int32'), intmax('int32'))
str = 'The range for int64 is:\n\t%d to %d ';
sprintf(str, intmin('int64'), intmax('int64'))
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 51/126
7/18/2019 MATLAB Quick Guide
Both the functions when called with the argument 'single', return the maximum and
minimum values that you can represent with the single-precision data type and when
called with the argument 'double', return the maximum and minimum values that you
can represent with the double-precision data type.
Example
The following example illustrates how to obtain the smallest and largest floating point
numbers. Create a script file and write the following code in it −
Live Demo
% displaying the smallest and largest single-precision
% floating point number
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
MATLAB - Strings
Creating a character string is quite simple in MATLAB. In fact, we have used it many
times. For example, you type the following in the command prompt −
Live Demo
my_string = 'Tutorials Point'
MATLAB will execute the above statement and return the following result −
MATLAB considers all variables as arrays, and strings are considered as character
arrays. Let us use the whos command to check the variable created above −
whos
MATLAB will execute the above statement and return the following result −
Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert
the characters in the string to their numeric codes. The char function converts the
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 52/126
7/18/2019 MATLAB Quick Guide
Example
Create a script file and type the following code into it −
Live Demo
my_string = 'Tutorial''s Point';
str_ascii = uint8(my_string) % 8-bit ascii values
str_back_to_char= char(str_ascii)
str_16bit = uint16(my_string) % 16-bit ascii values
str_back_to_char = char(str_16bit)
str_ascii =
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
Using the MATLAB concatenation operator [] and separating each row with a
semicolon (;). Please note that in this method each row must contain the same
number of characters. For strings with different lengths, you should pad with
space characters as needed.
Using the char function. If the strings are of different lengths, char pads the
shorter strings with trailing blanks so that each row has the same number of
characters.
Example
Create a script file and type the following code into it −
Live Demo
doc_profile = ['Zara Ali '; ...
'Sr. Surgeon '; ...
'R N Tagore Cardiology Research Center']
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 53/126
7/18/2019 MATLAB Quick Guide
doc_profile = char('Zara Ali', 'Sr. Surgeon', ...
'RN Tagore Cardiology Research Center')
doc_profile =
Zara Ali
Sr. Surgeon
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali
Sr. Surgeon
RN Tagore Cardiology Research Center
Using the MATLAB concatenation operator, [] and separating the input strings
with a comma or a space. This method preserves any trailing spaces in the
input arrays.
Using the string concatenation function, strcat. This method removes trailing
spaces in the inputs.
Example
Create a script file and type the following code into it −
Live Demo
name = 'Zara Ali ';
position = 'Sr. Surgeon ';
worksAt = 'R N Tagore Cardiology Research Center';
profile = [name ', ' position ', ' worksAt]
profile = strcat(name, ', ', position, ', ', worksAt)
However, a more efficient way to combine the strings is to convert the resulting array
into a cell array.
MATLAB cell array can hold different sizes and types of data in an array. Cell arrays
provide a more flexible way to store strings of varying length.
The cellstr function converts a character array into a cell array of strings.
Example
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 54/126
7/18/2019 MATLAB Quick Guide
{
[1,1] = Zara Ali
[2,1] = Sr. Surgeon
[3,1] = R N Tagore Cardiology Research Center
}
Function Purpose
Functions for storing text in character arrays, combine character arrays, etc.
Examples
The following examples illustrate some of the above-mentioned string functions −
FORMATTING STRINGS
Create a script file and type the following code into it −
Live Demo
A = pi*1000*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 56/126
7/18/2019 MATLAB Quick Guide
ans = 3141.592654
3141.59
+3141.59
3141.59
000003141.59
JOINING STRINGS
Create a script file and type the following code into it −
Live Demo
%cell array of strings
str_array = {'red','blue','green', 'yellow', 'orange'};
str1 = red-blue-green-yellow-orange
str2 = red,blue,green,yellow,orange
new_student =
{
[1,1] = Poulomi Dutta
}
first_names =
{
[1,1] = Zara
[1,2] = Neha
[1,3] = Monica
[1,4] = Madhu
[1,5] = Madhu
[1,6] = Bhawna
[1,7] = Nuha
[1,8] = Reva
[1,9] = Sunaina
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 57/126
7/18/2019 MATLAB Quick Guide
[1,10] = Sofia
}
COMPARING STRINGS
Create a script file and type the following code into it −
Live Demo
str1 = 'This is test'
str2 = 'This is text'
if (strcmp(str1, str2))
sprintf('%s and %s are equal', str1, str2)
else
sprintf('%s and %s are not equal', str1, str2)
end
MATLAB - Functions
A function is a group of statements that together perform a task. In MATLAB, functions
are defined in separate files. The name of the file and of the function should be the
same.
Functions operate on variables within their own workspace, which is also called the
local workspace, separate from the workspace you access at the MATLAB command
prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one
output arguments.
Example
The following function named mymax should be written in a file named mymax.m. It
takes five numbers as argument and returns the maximum of the numbers.
Create a function file, named mymax.m and type the following code in it −
max = n4;
end
if(n5 > max)
max = n5;
end
The first line of a function starts with the keyword function. It gives the name of the
function and order of arguments. In our example, the mymax function has five input
arguments and one output argument.
The comment lines that come right after the function statement provide the help text.
These lines are printed when you type −
help mymax
MATLAB will execute the above statement and return the following result −
MATLAB will execute the above statement and return the following result −
ans = 89
Anonymous Functions
An anonymous function is like an inline function in traditional programming languages,
defined within a single MATLAB statement. It consists of a single MATLAB expression
and any number of input and output arguments.
You can define an anonymous function right at the MATLAB command line or within a
function or script.
This way you can create simple functions without having to create a file for them.
f = @(arglist)expression
Example
In this example, we will write an anonymous function named power, which will take two
numbers as input and return first number raised to the power of the second number.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 59/126
7/18/2019 MATLAB Quick Guide
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459
Primary functions can be called from outside of the file that defines them, either from
command line or from other functions, but sub-functions cannot be called from
command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions within
the function file that defines them.
Example
Let us write a function named quadratic that would calculate the roots of a quadratic
equation. The function would take three inputs, the quadratic co-efficient, the linear co-
efficient and the constant term. It would return the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-
function disc, which calculates the discriminant.
quadratic(2,4,-4)
MATLAB will execute the above statement and return the following result −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 60/126
7/18/2019 MATLAB Quick Guide
ans = 0.7321
Nested Functions
You can define functions within the body of another function. These are called nested
functions. A nested function contains any or all of the components of any other
function.
Nested functions are defined within the scope of another function and they share access
to the containing function's workspace.
Example
Let us rewrite the function quadratic, from previous example, however, this time the
disc function will be a nested function.
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Private Functions
A private function is a primary function that is visible only to a limited group of other
functions. If you do not want to expose the implementation of a function(s), you can
create them as private functions.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 61/126
7/18/2019 MATLAB Quick Guide
Example
Let us rewrite the quadratic function. This time, however, the disc function calculating
the discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following function file
disc.m in it −
Create a function quadratic3.m in your working directory and type the following code in
it −
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3
quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Global Variables
Global variables can be shared by more than one function. For this, you need to declare
the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare the variable
at the command line.
The global declaration must occur before the variable is actually used in a function. It is
a good practice to use capital letters for the names of global variables to distinguish
them from other variables.
Example
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 62/126
7/18/2019 MATLAB Quick Guide
Let us create a function file named average.m and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500
A = importdata(filename)
1
Loads data into array A from the file denoted by filename.
A = importdata('-pastespecial')
2
Loads data from the system clipboard rather than from a file.
A = importdata(___, delimiterIn)
4 Loads data from ASCII file, filename, or the clipboard, reading numeric data
starting from line headerlinesIn+1.
Returns the detected delimiter character for the input ASCII file in
5
delimiterOut and the detected number of header lines in headerlinesOut,
using any of the input arguments in the previous syntaxes.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 63/126
7/18/2019 MATLAB Quick Guide
By default, Octave does not have support for importdata() function, so you will
have to search and install this package to make following examples work with
your Octave installation.
Example 1
Let us load and display an image file. Create a script file and type the following code in
it −
filename = 'smile.jpg';
A = importdata(filename);
image(A);
When you run the file, MATLAB displays the image file. However, you must store it in
the current directory.
Example 2
In this example, we import a text file and specify Delimiter and Column Header. Let us
create a space-delimited ASCII file with column headers, named weeklydata.txt.
filename = 'weeklydata.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
% View data
for k = [1:7]
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 64/126
7/18/2019 MATLAB Quick Guide
disp(A.colheaders{1, k})
disp(A.data(:, k))
disp(' ')
end
SunDay
95.0100
73.1100
60.6800
48.6000
89.1300
MonDay
76.2100
45.6500
41.8500
82.1400
44.4700
TuesDay
61.5400
79.1900
92.1800
73.8200
57.6300
WednesDay
40.5700
93.5500
91.6900
41.0300
89.3600
ThursDay
55.7900
75.2900
81.3200
0.9900
13.8900
FriDay
70.2800
69.8700
90.3800
67.2200
19.8800
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 65/126
7/18/2019 MATLAB Quick Guide
SaturDay
81.5300
74.6800
74.5100
93.1800
46.6000
Example 3
In this example, let us import data from clipboard.
Mathematics is simple
A = importdata('-pastespecial')
A =
'Mathematics is simple'
MATLAB provides the following functions for read and write operations at the byte or
character level −
Function Description
The fgetl and fgets functions read one line of a file at a time, where a newline
character separates each line.
The fread function reads a stream of data at the byte or bit level.
Example
We have a text data file 'myfile.txt' saved in our working directory. The file stores
rainfall data for three months; June, July and August for the year 2012.
The data in myfile.txt contains repeated sets of time, month and rainfall measurements
at five places. The header data stores the number of months M; so we have M sets of
measurements.
Rainfall Data
Months: June, July, August
M = 3
12:00:00
June-2012
17.21 28.52 39.78 16.55 23.67
19.15 0.35 17.57 NaN 12.01
17.92 28.49 17.40 17.06 11.09
9.59 9.33 NaN 0.31 0.23
10.46 13.17 NaN 14.89 19.33
20.97 19.50 17.65 14.45 14.00
18.23 10.34 17.95 16.46 19.34
09:10:02
July-2012
12.76 16.94 14.38 11.86 16.89
20.46 23.17 NaN 24.89 19.33
30.97 49.50 47.65 24.45 34.00
18.23 30.34 27.95 16.46 19.34
30.46 33.17 NaN 34.89 29.33
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 67/126
7/18/2019 MATLAB Quick Guide
We will import data from this file and display this data. Take the following steps −
Open the file with fopen function and get the file identifier.
Describe the data in the file with format specifiers, such as '%s' for a string,
'%d' for an integer, or '%f' for a floating-point number.
To skip literal characters in the file, include them in the format description. To
skip a data field, use an asterisk ('*') in the specifier.
For example, to read the headers and return the single value for M, we write −
By default, fscanf reads data according to our format description until it does
not find any match for the data, or it reaches the end of the file. Here we will
use for loop for reading 3 sets of data and each time, it will read 7 rows and 5
columns.
We will create a structure named mydata in the workspace to store data read
from the file. This structure has three fields - time, month, and raindata array.
filename = '/data/myfile.txt';
rows = 7;
cols = 5;
12:00:00
June-2012
17.2100 17.5700 11.0900 13.1700 14.4500
28.5200 NaN 9.5900 NaN 14.0000
39.7800 12.0100 9.3300 14.8900 18.2300
16.5500 17.9200 NaN 19.3300 10.3400
23.6700 28.4900 0.3100 20.9700 17.9500
19.1500 17.4000 0.2300 19.5000 16.4600
0.3500 17.0600 10.4600 17.6500 19.3400
09:10:02
July-2012
12.7600 NaN 34.0000 33.1700 24.4500
16.9400 24.8900 18.2300 NaN 34.0000
14.3800 19.3300 30.3400 34.8900 28.6700
11.8600 30.9700 27.9500 29.3300 30.3400
16.8900 49.5000 16.4600 30.9700 27.9500
20.4600 47.6500 19.3400 49.5000 36.4600
23.1700 24.4500 30.4600 47.6500 29.3400
15:03:40
August-2012
17.0900 13.4800 27.2100 11.4500 25.0500
16.5500 22.5500 26.7900 13.4800 27.2100
19.5900 24.0100 24.9800 22.5500 26.7900
17.2500 NaN 12.2300 24.0100 24.9800
19.2200 21.1900 16.9900 NaN 12.2300
17.5400 25.8500 18.6700 21.1900 16.9900
11.4500 25.0500 17.5400 25.8500 18.6700
Diary (or log) file of keystrokes and the resulting text output.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 69/126
7/18/2019 MATLAB Quick Guide
MEX-file to access your C/C++ or Fortran routine that writes to a particular text
file format.
There are two ways to export a numeric array as a delimited ASCII data file −
where, my_data.out is the delimited ASCII data file created, num_array is a numeric
array and −ascii is the specifier.
where, my_data.out is the delimited ASCII data file created, num_array is a numeric
array and dlm_char is the delimiter character.
Example
The following example demonstrates the concept. Create a script file and type the
following code −
Live Demo
num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
1 2 3 4
4 5 6 7
7 8 9 0
Please note that the save -ascii command and the dlmwrite function does not work with
cell arrays as input. To create a delimited ASCII file from the contents of a cell array,
you can
Either, convert the cell array to a matrix using the cell2mat function
If you use the save function to write a character array to an ASCII file, it writes the
ASCII equivalent of the characters to the file.
MATLAB executes the above statements and displays the following result. which is the
characters of the string 'hello' in 8-digit ASCII format.
diary
Optionally, you can give the name of the log file, say −
diary logdata.out
diary off
As in low-level I/O file activities, before exporting, you need to open or create a file
with the fopen function and get the file identifier. By default, fopen opens a file for
read-only access. You should specify the permission to write or append, such as 'w' or
'a'.
After processing the file, you need to close it with fclose(fid) function.
Example
Create a script file and type the following code in it −
Live Demo
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 71/126
7/18/2019 MATLAB Quick Guide
% Table Header
fprintf(fid, 'Log Function\n\n');
Log Function
0.000000 -Inf
10.000000 2.302585
20.000000 2.995732
30.000000 3.401197
40.000000 3.688879
50.000000 3.912023
60.000000 4.094345
70.000000 4.248495
80.000000 4.382027
90.000000 4.499810
100.000000 4.605170
MATLAB - Plotting
To plot the graph of a function, you need to take the following steps −
Define x, by specifying the range of values for the variable x, for which the
function is to be plotted
Following example would demonstrate the concept. Let us plot the simple function y =
x for the range of values for x from 0 to 100, with an increment of 5.
x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 72/126
7/18/2019 MATLAB Quick Guide
Let us take one more example to plot the function y = x2. In this example, we will draw
two graphs with the same function, but in second time, we will reduce the value of
increment. Please note that as we decrease the increment, the graph becomes
smoother.
x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −
x = [-100:5:100];
y = x.^2;
plot(x, y)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 73/126
7/18/2019 MATLAB Quick Guide
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale
factors and the spaces on both axes.
Example
Create a script file and type the following code −
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 74/126
7/18/2019 MATLAB Quick Guide
Example
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 75/126
7/18/2019 MATLAB Quick Guide
Code Color
w White
k Black
b Blue
r Red
c Cyan
g Green
m Magenta
y Yellow
Example
Let us draw the graph of two polynomials
g(x) = 5x3 + 9x + 2
When you run the file, MATLAB generates the following graph −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 76/126
7/18/2019 MATLAB Quick Guide
The axis command allows you to set the axis scales. You can provide minimum and
maximum values for x and y axes using the axis command in the following way −
Example
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
When you run the file, MATLAB generates the following graph −
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a
subplot. The subplot command is used for creating subplots.
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies
where to put a particular plot.
Each plot created with the subplot command can have its own characteristics. Following
example demonstrates the concept −
Example
Let us generate two plots −
y = e−1.5xsin(10x)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 77/126
7/18/2019 MATLAB Quick Guide
y = e−2xsin(10x)
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])
When you run the file, MATLAB generates the following graph −
MATLAB - Graphics
This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We
will discuss −
Drawing contours
Example
Let us have an imaginary classroom with 10 students. We know the percent of marks
obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw
the bar chart for this data.
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 78/126
7/18/2019 MATLAB Quick Guide
bar(x,y), xlabel('Student'),ylabel('Score'),
title('First Sem:')
print -deps graph.eps
When you run the file, MATLAB displays the following bar chart −
Drawing Contours
A contour line of a function of two variables is a curve along which the function has a
constant value. Contour lines are used for creating contour maps by joining points of
equal elevation above a given level, such as mean sea level.
Example
Let us generate a contour map that shows the contour lines for a given function g = f(x,
y). This function has two variables. So, we will have to generate two independent
variables, i.e., two data sets x and y. This is done by calling the meshgrid command.
The meshgrid command is used for generating a matrix of elements that give the
range over x and y along with the specification of increment in each case.
When you run the file, MATLAB displays the following contour map −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 79/126
7/18/2019 MATLAB Quick Guide
When you run the file, MATLAB displays the following contour map −
As before, to define g, we first create a set of (x,y) points over the domain of the
function using the meshgrid command. Next, we assign the function itself. Finally, we
use the surf command to create a surface plot.
Example
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 80/126
7/18/2019 MATLAB Quick Guide
2 2
Let us create a 3D surface map for the function g = xe-(x + y )
[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 −
You can also use the mesh command to generate a three-dimensional surface.
However, the surf command displays both the connecting lines and the faces of the
surface in color, whereas, the mesh command creates a wireframe surface with colored
lines connecting the defining points.
MATLAB - Algebra
So far, we have seen that all the examples work in MATLAB as well as its GNU,
alternatively called Octave. But for solving basic algebraic equations, both MATLAB and
Octave are little different, so we will try to cover MATLAB and Octave in separate
sections.
solve('x-5=0')
MATLAB will execute the above statement and return the following result −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 81/126
7/18/2019 MATLAB Quick Guide
ans =
5
y = solve('x-5 = 0')
MATLAB will execute the above statement and return the following result −
y =
5
You may even not include the right hand side of the equation −
solve('x-5')
MATLAB will execute the above statement and return the following result −
ans =
5
If the equation involves multiple symbols, then MATLAB by default assumes that you
are solving for x, however, the solve function has another form −
solve(equation, variable)
For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should
write −
solve('v-u-3*t^2=0', 'v')
MATLAB will execute the above statement and return the following result −
ans =
3*t^2 + u
Octave will execute the above statement and return the following result −
ans = 5
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 82/126
7/18/2019 MATLAB Quick Guide
Octave will execute the above statement and return the following result −
y = 5
The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file
and type the following code −
solve('(x-3)^2*(x-7)=0')
MATLAB will execute the above statement and return the following result −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 83/126
7/18/2019 MATLAB Quick Guide
ans =
3
3
7
In case of higher order equations, roots are long containing many terms. You can get
the numerical value of such roots by converting them to double. The following example
solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0.
Please note that the last two roots are complex numbers.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 84/126
7/18/2019 MATLAB Quick Guide
5x + 9y = 5
3x – 6y = 4
ans =
22/19
ans =
-5/57
In same way, you can solve larger linear systems. Consider the following set of
equations −
x + 3y -2z = 5
3x + 5y + 6z = 7
2x + 4y + 3z = 8
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 85/126
7/18/2019 MATLAB Quick Guide
We have a little different approach to solve a system of 'n' linear equations in 'n'
unknowns. Let us take up a simple example to demonstrate this use.
5x + 9y = 5
3x – 6y = 4
Such a system of linear equations can be written as the single matrix equation Ax = b,
where A is the coefficient matrix, b is the column vector containing the right-hand side
of the linear equations and x is the column vector representing the solution as shown in
the below program −
ans =
1.157895
-0.087719
In same way, you can solve larger linear systems as given below −
x + 3y -2z = 5
3x + 5y + 6z = 7
2x + 4y + 3z = 8
When you work with many symbolic functions, you should declare that your variables
are symbolic.
% collecting equations
collect(x^3 *(x-7))
collect(x^4*(x-3)*(x-5))
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 86/126
7/18/2019 MATLAB Quick Guide
ans =
x^2 + 4*x - 45
ans =
x^4 + x^3 - 43*x^2 + 23*x + 210
ans =
2*cos(x)*sin(x)
ans =
cos(x)*cos(y) - sin(x)*sin(y)
ans =
x^4 - 7*x^3
ans =
x^6 - 8*x^5 + 15*x^4
When you work with many symbolic functions, you should declare that your variables
are symbolic but Octave has different approach to define symbolic variables. Notice the
use of Sin and Cos, which are also defined in symbolic package.
% expanding equations
expand((x-5)*(x+9))
expand((x+2)*(x-3)*(x-5)*(x+7))
expand(Sin(2*x))
expand(Cos(x+y))
% collecting equations
collect(x^3 *(x-7), z)
collect(x^4*(x-3)*(x-5), z)
ans =
-45.0+x^2+(4.0)*x
ans =
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 87/126
7/18/2019 MATLAB Quick Guide
210.0+x^4-(43.0)*x^2+x^3+(23.0)*x
ans =
sin((2.0)*x)
ans =
cos(y+x)
ans =
x^(3.0)*(-7.0+x)
ans =
(-3.0+x)*x^(4.0)*(-5.0+x)
Example
Create a script file and type the following code −
syms x
syms y
factor(x^3 - y^3)
factor([x^2-y^2,x^3+y^3])
simplify((x^4-16)/(x^2-4))
ans =
(x - y)*(x^2 + x*y + y^2)
ans =
[ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)]
ans =
x^2 + 4
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.
This chapter will deal with problems of calculus. In this chapter, we will discuss pre-
calculus concepts i.e., calculating limits of functions and verifying the properties of
limits.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 88/126
7/18/2019 MATLAB Quick Guide
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.
Calculating Limits
MATLAB provides the limit function for calculating limits. In its most basic form, the
limit function 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 function falls in the realm of symbolic computing; you need to use the syms
function 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.
limit((x - 3)/(x-1),1)
MATLAB will execute the above statement and return the following result −
ans =
NaN
limit(x^2 + 5, 3)
MATLAB will execute the above statement and return the following result −
ans =
14
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 89/126
7/18/2019 MATLAB Quick Guide
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
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)
l1 =
17
l2 =
17
lAdd =
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 90/126
7/18/2019 MATLAB Quick Guide
34
lSub =
0
lMult =
289
lDiv =
1
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
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 limit are not equal, the
limit does not exist.
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 −
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
l =
-1
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 92/126
7/18/2019 MATLAB Quick Guide
r =
1
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
t = sym("t");
f = 3*t^2 + 2*t^(-2);
differentiate(f,t)
ans =
-(4.0)*t^(-3.0)+(6.0)*t
Rule 1
For any functions f and g and any real numbers a and b are the derivative of the
function −
Rule 2
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 93/126
7/18/2019 MATLAB Quick Guide
The sum and subtraction rules state that if f and g are two functions, f' and g' are
their derivatives respectively, then,
Rule 3
The product rule states that if f and g are two functions, f' and g' are their derivatives
respectively, then,
Rule 4
The quotient rule states that if f and g are two functions, f' and g' are their derivatives
respectively, then,
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 that the derivative of any constant is zero, i.e., if y = k,
any constant, then
f' = 0
Rule 6
The chain rule states that, 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 −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 94/126
7/18/2019 MATLAB Quick Guide
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
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)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 95/126
7/18/2019 MATLAB Quick Guide
f = (x^2 + 1)^17
der5 = differentiate(f,x)
f = (t^3 + 3* t^2 + 5*t -9)^(-6)
der6 = differentiate(f,t)
f =
(2.0+x)*(3.0+x^(2.0))
der1 =
3.0+x^(2.0)+(2.0)*(2.0+x)*x
f =
(t^(3.0)+sqrt(t))*(3.0+t^(2.0))
der2 =
(2.0)*(t^(3.0)+sqrt(t))*t+((3.0)*t^(2.0)+(0.5)*t^(-0.5))*(3.0+t^(2.0))
f =
(1.0+x^(2.0)-(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))
der3 =
(-2.0+(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))+((9.0)*x^(2.0)-(10.0)*x)*(1.0+x^(2.0)-(2.0)*x)
f =
(1.0+x^(3.0))^(-1)*((2.0)*x^(2.0)+(3.0)*x)
der4 =
(1.0+x^(3.0))^(-1)*(3.0+(4.0)*x)-(3.0)*(1.0+x^(3.0))^(-2)*x^(2.0)*((2.0)*x^(2.0)+(3.0)*x)
f =
(1.0+x^(2.0))^(17.0)
der5 =
(34.0)*(1.0+x^(2.0))^(16.0)*x
f =
(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-6.0)
der6 =
-(6.0)*(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-7.0)*(5.0+(3.0)*t^(2.0)+(6.0)*t)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 96/126
7/18/2019 MATLAB Quick Guide
The following table provides the derivatives of commonly used exponential, logarithmic
and trigonometric functions −
Function Derivative
ex ex
ln x 1/x
lncx 1/x.ln c
xx xx.(1 + ln x)
sin(x) cos(x)
cos(x) -sin(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 −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 97/126
7/18/2019 MATLAB Quick Guide
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)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 98/126
7/18/2019 MATLAB Quick Guide
ans =
exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2
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)
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)
y =
exp(x)
ans =
exp(x)
y =
x^(9.0)
ans =
(9.0)*x^(8.0)
y =
sin(x)
ans =
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 99/126
7/18/2019 MATLAB Quick Guide
cos(x)
y =
tan(x)
ans =
1+tan(x)^2
y =
cos(x)
ans =
-sin(x)
y =
log(x)
ans =
x^(-1)
y =
sin(x)^(2.0)
ans =
(2.0)*sin(x)*cos(x)
y =
cos(1.0+(2.0)*x+(3.0)*x^(2.0))
ans =
-(2.0+(6.0)*x)*sin(1.0+(2.0)*x+(3.0)*x^(2.0))
y =
sin(x)^(-1)*exp(x)
ans =
sin(x)^(-1)*exp(x)-sin(x)^(-2)*cos(x)*exp(x)
f = x*exp(-3*x);
diff(f, 2)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 100/126
7/18/2019 MATLAB Quick Guide
ans =
9*x*exp(-3*x) - 6*exp(-3*x)
x = sym("x");
f = x*Exp(-3*x);
differentiate(f, x, 2)
ans =
(9.0)*exp(-(3.0)*x)*x-(6.0)*exp(-(3.0)*x)
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.
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);
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');
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 101/126
7/18/2019 MATLAB Quick Guide
end
disp('Value of LHS is: '), disp(lhs);
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
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 102/126
7/18/2019 MATLAB Quick Guide
x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");
ezplot(y)
print -deps graph.eps
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])
x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");
g = diff(y)
g =
6*x^2 + 6*x - 12
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 103/126
7/18/2019 MATLAB Quick Guide
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
g =
-12.0+(6.0)*x+(6.0)*x^(2.0)
Let us solve the derivative function, g, to get the values where it becomes
zero.
s = solve(g)
s =
1
-2
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
roots([6, 6, -12])
g =
-12.0+(6.0)*x^(2.0)+(6.0)*x
ans =
-2
1
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.
ans =
10
ans =
37
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 104/126
7/18/2019 MATLAB Quick Guide
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)
ans =
10.0
ans =
37.0-4.6734207789940138748E-18*I
Therefore, The minimum and maximum values on the function f(x) = 2x3 + 3x2 − 12x
+ 17, in the interval [-2,2] are 10 and 37.
The most basic form of the dsolve command for finding the solution to a single
equation is
dsolve('eqn')
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 −
Let us take up a simple example of a first order differential equation: y' = 5y.
s = dsolve('Dy = 5*y')
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 105/126
7/18/2019 MATLAB Quick Guide
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.
ans =
exp(t)/2 - (3*exp(-t))/2
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.
In symbols −
∫ 2xdx = x2.
∫ 2xdx = x2 + c.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 106/126
7/18/2019 MATLAB Quick Guide
int(f);
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)
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))
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 107/126
7/18/2019 MATLAB Quick Guide
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 function returns an expression in a more readable format.
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))
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
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 108/126
7/18/2019 MATLAB Quick Guide
The int function can be used for definite integration by passing the limits over which
you want to calculate the integral.
To calculate
we write,
int(x, a, b)
we write −
int(x, 4, 9)
MATLAB executes the above statement and returns the following result −
ans =
65/2
x = sym("x");
f = x;
c = [1, 0];
integral = polyint(c);
Area:
32.500
f = inline("x");
[a, ierror, nfneval] = quad(f, 4, 9);
Area:
32.500
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.
a =
23/4
Area:
5.7500
x = sym("x");
f = x^3 - 2*x +5;
c = [1, 0, -2, 5];
integral = polyint(c);
Area:
5.7500
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 110/126
7/18/2019 MATLAB Quick Guide
x = sym("x");
f = inline("x^3 - 2*x +5");
Area:
5.7500
Example 2
Find the area under the curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9.
f = x^2*cos(x);
ezplot(f, [-4,9])
a = int(f, -4, 9)
disp('Area: '), disp(double(a));
a =
8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)
Area:
0.3326
x = sym("x");
f = inline("x^2*cos(x)");
ezplot(f, [-4,9])
print -deps graph.eps
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 −
Live Demo
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 −
Live Demo
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
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 =
Columns 1 through 3:
Columns 4 and 5:
p = polyfit(x,y,n)
Example
Create a script file and type the following code −
Live Demo
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
When you run the file, MATLAB displays the following result −
p =
4.1056 -47.9607 222.2598 -362.7453 191.1250
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.
MATLAB provides the laplace, fourier and fft commands to work with Laplace, Fourier
and Fast Fourier transforms.
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.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 114/126
7/18/2019 MATLAB Quick Guide
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))
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)
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))
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 115/126
7/18/2019 MATLAB Quick Guide
ilaplace(w/(s^2 + w^2))
ilaplace(s/(s^2 + w^2))
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)
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 −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 116/126
7/18/2019 MATLAB Quick Guide
FT =
(2^(1/2)*pi^(1/2)*exp(-w^2/8))/2
ezplot(FT)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 117/126
7/18/2019 MATLAB Quick Guide
f = ifourier(-2*exp(-abs(w)))
MATLAB will execute the above statement and display the result −
f =
-2/(pi*(x^2 + 1))
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 −
2 2
This example creates a 3D surface map for the function g = xe-(x + y ). 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 −
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 118/126
7/18/2019 MATLAB Quick Guide
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));
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 119/126
7/18/2019 MATLAB Quick Guide
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 −
x = sym("x");
f = inline("x^2*cos(x)");
ezplot(f, [-4,9])
print -deps graph.eps
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 modelling, 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
There are several other add-on products provided by MathWorks and third-party
hardware and software products that are available for use with Simulink.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 120/126
7/18/2019 MATLAB Quick Guide
Simulink Design Verifier allows you to identify design errors and to generate 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.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 121/126
7/18/2019 MATLAB Quick Guide
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.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 122/126
7/18/2019 MATLAB Quick Guide
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, two 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).
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 123/126
7/18/2019 MATLAB Quick Guide
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.
Select 'Sinks' from the library and drag a 'Scope' block into the model.
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 124/126
7/18/2019 MATLAB Quick Guide
Drag a signal line from the output of the Sine Wave block to the input of the Scope
block.
Run the simulation by pressing the 'Run' button, keeping all parameters default (you
can change them from the Simulation menu)
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 125/126
7/18/2019 MATLAB Quick Guide
https://www.tutorialspoint.com/matlab/matlab_quick_guide.htm 126/126