0-12MATLAB Overview
0-12MATLAB Overview
Q: What is MATLAB?
MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive
environment for numerical computation, visualization and programming.
MATLAB is developed by MathWorks.
It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of
user interfaces; interfacing with programs written in other languages, including C, C++, Java, and
FORTRAN; analyze data; develop algorithms; and create models and applications.
An algorithm is a way to tell computer how to do a specific task.
It has numerous built-in commands and math functions that help you in mathematical calculations,
generating plots, and performing numerical methods.
MATLAB's Power of Computational Mathematics
Q: Features of MATLAB.
Following are the basic features of MATLAB −
It is a high-level language for numerical computation, visualization and application development.
It also provides an interactive environment for iterative exploration, design and problem solving.
It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis,
filtering, optimization, numerical integration and solving ordinary differential equations.
It provides built-in graphics for visualizing data and tools for creating custom plots.
MATLAB's programming interface gives development tools for improving code quality
maintainability and maximizing performance.
It provides tools for building applications with custom graphical interfaces.
It provides functions for integrating MATLAB based algorithms with external applications and
languages such as C, Java, .NET and Microsoft Excel.
Q: 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 −
Signal Processing and Communications
Image and Video Processing
Control Systems
Test and Measurement
Computational Finance
Computational Biology
Dealing with Matrices and Arrays
2-D and 3-D Plotting and graphics
Linear Algebra
Algebraic Equations
Non-linear Functions
Statistics
Data Analysis
Calculus and Differential Equations
Numerical Calculations
Integration
Transforms
Curve Fitting
Various other special functions
ans =
10 0 55 0
>> cumsum(x) ans =
0 1 3 6 10 15 21 28 36
45 55
>> cumprod(x)
ans =
000000000
0 0 % Why zeros?
Functions
A function is a simple set of instructions which accepts some inputs and returns outputs. There are a wide
range of inbuilt functions in MATLAB for different application and they can be called anywhere with
proper inputs. A function call generally has the following syntax
Functions and scripts are both M-files, but there are a few differences between them. As we saw, the first
line defines whether the M-file is a function or a script. A function has a particular set of inputs and
outputs, while a script doesn’t. A script can use all the variables created in the MATLAB workspace, but
a function can only use the variables specially passed to it. After the execution is over, a script returns all
the variables to the workspace while a function only returns the variables listed as outputs and deletes the
rest of the variables. Scripts use the same copy of a variable in the MATLAB workspace and modifying
any variable in any script will affect the original copy in the workspace while a function creates a new
copy of all the variables when they are called and any modification to these variables doesn’t affect the
original variables. In other words, when a function is called from a workspace, the function call creates a
new workspace, copies variables to it, computes outputs and returns these variables to the calling
workspace, deleting its own workspace. You can also call a script from a function. In that case, the script
will use the calling function’s workspace and the variables created by this script call will also get deleted
when the calling function finishes its execution.
Special Matrices
MATLAB - Basic Syntax 1
MATLAB environment behaves like a super-complex calculator. You can enter commands at the >>
command prompt.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it
right away.
Hands on Practice
>> 5 + 5 ans = 10
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result
returned is −
Another example,
>> 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,
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,
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result
returned is −
ans = 1.4860e+04
Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output
for an expression, add a semicolon after the expression.
For example,
>> x = 3;
>> y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result
returned is −
y= 8
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
>> x = 9 % assign the value 9 to x
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.
The save command is used for saving all the variables in the workspace, as a file with .mat extension, in
the current directory.
For example,
You can reload the file anytime later using the load command.
B= B=
The command terminated with a semicolon suppress MATLAB from displaying the variables
value.
>> B = [23, 35.3] % no semicolon >> B = [23, 35.3]; % with semicolon
B=
23.0000 35.3000
MATLAB – Variables-2
Examples:
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.
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.
Variables must have values before they are used.
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,
>> sqrt(78)
MATLAB will execute the above statement and return the following result −
ans = 8.8318
>>sqrt(78);
>>9876/ans
MATLAB will execute the above statement and return the following result −
ans = 1118.2
>>x = 7 * 8;
>>y = x * 7.89
MATLAB will execute the above statement and return the following result −
y = 441.84
Multiple Assignments
You can have multiple assignments on the same line. For example,
>>a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14
The who command displays all the variable names you have used.
>>who
MATLAB will execute the above statement and return the following result −
>> who
ans p q
>> whos
Name Size Bytes Class Attributes
The clear command deletes all (or the specified) variable(s) from the memory.
clear x % it will delete x, won't display anything
clear % it will delete all variables in the workspace
Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For example,
M=
0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
(2) Selecting displays formats from the command window pull down menus, e.g.,
(3) Formatted output from script files is also possible, that is the format of variables printed to the
screen can be made unique for each variable you want the program to print, and custom text be
distributed around the numeric values
By default, MATLAB displays numbers with four decimal place values. This is known as short format.
However, if you want more precision, you need to use the format command.
• Globally the display format for the command window can be changed
by:
– Typing commands directly, e.g.,
format short % four decimal digits
format long % 14 decimal digits
format short e % short with scientific notation
format long e % long with scientific notation
For example −
x=
17.231981640639408
Another example,
x=
17.2320
The format bank command rounds numbers to two decimal places. For example,
x=
17.23
The format short e command allows displaying in exponential form with four decimal places plus the
exponent.
For example,
x=
1.7232e+01
The format long e command allows displaying in exponential form with four decimal places plus the
exponent. For example,
x=
1.723198164063941e+01
The format rat command gives the closest rational expression resulting from a calculation. For example,
x=
7651/444
– Selecting displays formats from the command window pull down menus, e.g.,
Name Meaning
pi The number π
>> i
ans =
0.0 + 1.0000i
>> j
ans =
0.0000 + 1.0000i
>> Inf
ans =
Inf
nan is the MATLAB representation for not-a-number; often a result of a 0/0 operation
>> nan
ans =
NaN
>> clock
ans =
1.0e+03 *
>> date
ans =
23-Aug-2006
eps is the smallest floating-point number by which two numbers can differ, e.g.,
>> eps
ans =
2.2204e-016
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.
Commands for Managing a Session
MATLAB provides various commands for managing a session. The following table provides all
such commands −
Command Purpose
%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
MATLAB - M-Files-4
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.
Functions − functions files are also program files with .m extension. Functions can accept inputs
and return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .mfiles.
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.
>> tutorial % tutorial is already saved as tutorial.m
x=
10
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.
Type the following code in the editor −
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
MATLAB does not require any type declaration or dimension statements. Whenever MATLAB
encounters a new variable name, it creates the variable and allocates appropriate memory space.
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.
Data Types Available in MATLAB
MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix
or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array
of any size.
The following table shows the most commonly used data types in MATLAB −
Sr.No. Data Type & Description
int8
1
8-bit signed integer
uint8
2
8-bit unsigned integer
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
9 single
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
13
array of indexed cells, each capable of storing an array of a different dimension and data type
structure
14 C-like structures, each structure having named fields capable of storing an array of a
different dimension and data type
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 −
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 −
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5678.9
c = 5679
Data Type Conversion
MATLAB provides various functions for converting, a value from one data type to another. The
following table shows the data type conversion functions −
Function Purpose
mat2cell Convert array to cell array with potentially different sized cells
is Detect state
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)
isscalar(x)
isnumeric(x)
When you run the file, it produces the following result −
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-6
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
MATLAB allows two different types of arithmetic operations −
Matrix arithmetic operations
Array arithmetic operations
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 −
Addition or unary plus. A+B adds the values stored in variables A and B. A and B
1 + must have the same size, unless one is a scalar. A scalar can be added to a matrix of
any size.
Subtraction or unary minus. A-B subtracts the value of B from A. A and B must
2 - have the same size, unless one is a scalar. A scalar can be subtracted from a matrix
of any size.
Slash or matrix right division, Right-division operator.. B/A is roughly the same as
5 /
B*inv(A). More precisely, B/A = (A'\B')'.
Array right division, Array right-division operator. A./B is the matrix with
6 ./ elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a
scalar.
Array left division, Array left-division operator. A.\B is the matrix with elements
8 .\
B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar.
Array power, Scalar exponentiation operator. A.^B is the matrix with elements
10 .^ A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a
scalar.
' Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices,
11
this is the complex conjugate transpose.
.' Array transpose. A.' is the array transpose of A. For complex matrices, this does
12
not involve conjugation.
>> a = 3.1;
>>b = 5.234;
>> c = a + b
c=
8.3340
>> c = a/b
c=
0.5923
>> c = a^b
c=
373.0672
2. Array Operations
When working with vectors and matrices we have the choice of performing operations element-
by-element or according to the rules of matrix algebra
In this section we are only interested in element-by-element operations
Basically element-by-element operations on vectors and matrices are the same as those of Table
A.2, except ‘.’ Must be added before the operator
Another related case is when a scalar operates on a vector or matrix
In this case the scalar is applied to each vector or matrix element in a like fashion
Examples:
>> A = [1 3 5 7]
>> B = 2.*A
B=
2 6 10 14
>> C = B./A % Vector-to-vector point wise C = 2 2 2 2
>> D = A.^3
D = 1 27 125 343
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.
The following table shows the relational operators available in MATLAB −
5 == Equal to
6 ~= Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions −
Element-wise − These operators operate on corresponding elements of logical arrays.
Short-circuit − These operators operate on scalar and, logical expressions.
Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are
the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the
logical short-circuit operators AND and OR.
o Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as
follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Example:
>> p=[0 1 0 1 1 0]
p=
0 1 0 1 1 0
>> q=[1 0 1 1 0 1]
q=
1 0 1 1 0 1
>> p&q
ans =
0 0 0 1 0 0
>> p=[0 1 0 1 1 0]
p=
0 1 0 1 1 0
>> q=[1 0 1 1 0 1]
q=
1 0 1 1 0 1
>> p|q
ans =
1 1 1 1 1 1
>> p=[0 1 0 1 1 0]
p=
0 1 0 1 1 0
>> q=[1 0 1 1 0 1]
q=
1 0 1 1 0 1
>> ~p
ans =
1×6 logical array
1 0 1 0 0 1
>> ~q
ans =
1×6 logical array
0 1 0 0 1 0
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise
not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations −
Function Purpose
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')
2 Treats each row of A and each row of B as single entities and returns the 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 vector
4
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 (false)
5
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')
Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and
6
logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output
of sortrows(A) are equal.
setdiff(A,B)
7 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 rows from A
8
that are not in B. The rows of the returned matrix are in sorted order.
The 'rows' option does not support cell arrays.
setxor
9
Sets exclusive OR of two arrays
union
10
Sets union of two arrays
unique
11
Unique values in array
. Decimal point.
= Assignment operator.
Colon Operator
To make matrix generation and addressing easier we use the colon operator
The colon operator is indeed powerful, and mastering it is essential to becoming a MATLAB
expert
– Here we use it to generate row vectors
>> A=[0:10]
A=
0 1 2 3 4 5 6 7 8 9 10
>> k = 0:6
k=
0 1 2 3 4 5 6
>> t = 0:.25:2
t=
0 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 1.7500 2.0000
>> t=[0:0.1:2]
t=
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000
1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000
>> s = -10:2:0
s=
-10 -8 -6 -4 -2 0
>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A=
1 2 3
4 5 6
7 8 9
A_col2 =
2
5
8
A_11 =
transpose operator
We can swap the rows and columns of a matrix using the transpose operator, e.g.,
A = [1, 2, 3];
>> A_transpose = A'
A_transpose =
1
2
3
Display columns in side-by-side
A simple formatting scheme to have MATLAB display the values of several equal length vectors side-by-
side is the following (actual MATLAB command line interaction)
ans =
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
Decision making structures require that the programmer should specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be
false.
Following is the general form of a typical decision making structure found in most of the programming
languages −
MATLAB provides following types of decision making statements. Click the following links to check
their detail −
Sr.No. Statement & Description
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.
if <expression>
% statement(s) will execute if the boolean expression is true
<statements>
End
If the expression evaluates to true, then the block of code inside the if statement will be executed.
If the expression evaluates to false, then the first set of code after the end statement will be executed.
Flow Diagram
Example
if <expression>
% statement(s) will execute if the boolean expression is true
<statement(s)>
else
<statement(s)>
% statement(s) will execute if the boolean expression is false
end
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else
block of code will be executed.
Flow Diagram
Example
An if statement can be followed by one (or more) optional elseif... and an else statement, which is very
useful to test various conditions.
When using if... elseif...else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Syntax
if <expression 1>
% Executes when the expression 1 is true
<statement(s)>
else
% executes when the none of the above condition is true
<statement(s)>
end
Example
It is always legal in MATLAB to nest if-else statements which means you can use one if or elseif
statement inside another if or elseif statement(s).
Syntax
if <expression 1>
% Executes when the boolean expression 1 is true
if <expression 2>
% Executes when the boolean expression 2 is true
end
end
You can nest elseif...else in the similar way as you have nested if statement.
Example
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
A switch block conditionally executes one set of statements from several choices. Each choice is covered
by a case statement.
An evaluated switch_expression is a scalar or string.
An evaluated case_expression is a scalar, a string or a cell array of scalars or strings.
The switch block tests each case until one of the cases is true. A case is true when −
For numbers, eq(case_expression,switch_expression).
For strings, strcmp(case_expression,switch_expression).
For objects that support the eq(case_expression,switch_expression).
For a cell array case_expression, at least one of the elements of the cell array matches
switch_expression, as defined above for numbers, strings and objects.
When a case is true, MATLAB executes the corresponding statements and then exits the switch block.
The otherwise block is optional and executes only when no case is true.
Syntax
switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end
Example
It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case
constants of the inner and outer switch contain common values, no conflicts will arise.
Syntax
case 'B'
fprintf('This B is part of inner switch' );
end
case 'B'
fprintf('This B is part of outer switch' );
end
Example
There may be a situation when you need to execute a block of code several number of times called a loop.
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.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages −
MATLAB provides following types of loops to handle looping requirements.
Sr. No. Loop Type & Description
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.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
Syntax
The syntax of a for loop in MATLAB is −
for index = values
<program statements>
...
end
values has one of the following forms −
Sr.No
Format & Description
.
initval:endval
1 increments the index variable from initval to endval by 1, and repeats execution of program
statements until index is greater than endval.
initval:step:endval
2
increments index by the value step on each iteration, or decrements when step is negative.
valArray
creates a column vector index from subsequent columns of array valArray on each iteration.
3 For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum
of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :).
The input valArray can be of any MATLAB data type, including a string, cell array, or struct.
Example 1
for a = 10:20 value of a: 10
fprintf('value of a: %d\n', a); value of a: 11
end value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
Example 2
for a = 1.0: -0.1: 0.0 1
disp(a) 0.90000
end 0.80000
0.70000
0.60000
0.50000
0.40000
0.30000
0.20000
0.10000
0
Example 3
for a = [24,18,17,23,28] 24
disp(a) 18
end 17
23
28
MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate
the concept.
Syntax
The syntax for a nested for loop statement in MATLAB is as follows −
for m = 1:j
for n = 1:k
<statements>;
end
end
The syntax for a nested while loop statement in MATLAB is as follows −
while <expression1>
while <expression2>
<statements>
end
end
Example
Let us use a nested for loop to display all the prime numbers from 1 to 100. Create a script file and type
the following code –
for i = 2:100 2 is prime
for j = 2:100 3 is prime
if(~mod(i,j)) 5 is prime
break; % if factor found, not prime 7 is prime
end 11 is prime
end 13 is prime
if(j > (i/j)) 17 is prime
fprintf('%d is prime\n', i); 19 is prime
end 23 is prime
end 29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
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.
The break statement terminates execution of for or while loop. Statements in the loop that appear after
the break statement are not executed.
In nested loops, break exits only from the loop in which it occurs. Control passes to the statement
following the end of that loop.
Flow Diagram
Example
a = 10; value of a: 10
% while loop execution value of a: 11
while (a < 20 ) value of a: 12
fprintf('value of a: %d\n', a); value of a: 13
a = a + 1; value of a: 14
if( a > 15) value of a: 15
% terminate the loop using break statement
break;
end
end
The continue statement is used for passing control to next iteration of for or while loop.
The continue statement in MATLAB works somewhat like the break statement. Instead of forcing
termination, however, 'continue' forces the next iteration of the loop to take place, skipping any code in
between.
Flow Diagram
Example
a = 9; value of a: 10
%while loop execution value of a: 11
while a < 20 value of a: 12
a = a + 1; value of a: 13
if a == 15 value of a: 14
% skip the iteration value of a: 16
continue; value of a: 17
end value of a: 18
fprintf('value of a: %d\n', a); value of a: 19
end value of a: 20
MATLAB – Arrays-9
Array
is the collection of homogeneous elements.
is a data structure.
It can be of 1D(e.g numerals, strings etc), 2D(e.g. pixel color info of an image), 3D(e.g data table) or any
n Dimensions.
The 2D array is called matrix.
The 1D array is called a vector.
The 0D array is called a scalar.
All variables of all data types in MATLAB are multidimensional arrays.
Define scalar
>> x = 10 x = 10
>> A = [3.1415] % A 1x1 matrix A = 3.1415
16 2 3 13
5 11 10 8
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.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
For example, let's create a two-dimensional array a.
a = [7 9 5; 6 1 9; 4 3 2] 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 −
>> a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9] a(:,:,1) =
7 9 5
6 1 9
4 3 2
a(:,:,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,
b = rand(4,3,2) b(:,:,1) =
b(:,:,2) =
We can also use the cat() function to build multidimensional arrays. It concatenates a list of
arrays along a specified dimension −
a = [9 8 7; 6 5 4; 3 2 1]; c(:,:,1) =
b = [1 2 3; 4 5 6; 7 8 9]; 9 8 7
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0]) 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
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.
Function Purpose
c=
8 9 7
2 3 1
5 6 4
Sorting Arrays
Create a script file and type the following code into it –
Cell Array
When a collection contains elements of different types, they can be represented using a cell array. A
multiline string can be better represented using cells since different elements in a cell can have a different
number of columns, hence strings with different lengths.
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,
C is the cell array;
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;
obj is One of the following −
o Java array or object
o .NET array of type System.String or System.Object
Example
c = cell(2, 5); c=
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 {
4 5} [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
}
Accessing Data in Cell Arrays
There are two ways to refer to the elements of a cell array −
Enclosing the indices in first bracket (), to refer to sets of cells
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.
Cell array indices in smooth parentheses refer to sets of cells.
For example –
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 ans =
4 5}; {
c(1:2,1:2) [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.
For example –
MATLAB – Vectors-10
>> C = [1, 2, 3; 4, 5, 6; 7, 8, 9] % a
3x3 matrix
>> A= [1 3 5 6 3 2] A=1 3 5 6 3 2
>> A=[1,3,5,6,3,2] A= 1 3 5 6 3 2
Column Vectors
A matrix with a single column is also known as a column vector.
Column vectors are created by enclosing the set of elements in square brackets, using semicolon to
delimit the elements.
>> c = [7; 8; 9; 10; 11] c=
7
8
9
10
11
>> A=[1;3;5;6;3;2] A=
1
3
5
6
3
2
>> A=[4;5]; Semicolon is used to separate A=
rows 4
5
>> C=[2;A] C=
2
4
5
>> C=[2; [4;5]] C=
2
4
5
When you reference a vector with a colon, such as v(:), all the components of the vector are listed.
Vector Operations
Appending Vectors c1 = [ 1; 2; 3; 4 ]; c=
c2 = [5; 6; 7; 8 ];
c = [c1; c2] 1
cMat = [c1,c2] 2
3
4
5
6
7
8
cMat =
1 5
2 6
3 7
4 8
Magnitude of a Vector v = [1: 2: 20]; sv: 36.469
sv = v.* v;
Vector Dot Product 1 = [2 3 4]; dp =
v2 = [1 2 3];
dp = dot(v1, v2); 20
MATLAB – Matrix-11
For example, to refer to the element in the 2nd row and 5th column, of the matrix a, we type –
>> a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; ans = 6
>> a(2,5)
To reference all the elements in the mth column we type a(:,m).
Let us create a column vector v, from the elements of the 4th row of the matrix a –
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; v=
v = a(:,4) 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 −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; ans =
a(:, 2:3) 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.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; ans =
a(:, 2:3) 2 3
3 4
4 5
5 6
We can create a sub-matrix taking a sub-part of a matrix.
For example, let us create a sub-matrix sa taking the inner subpart of a −
3 4 5
4 5 6
To do this, write –
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; sa =
sa = a(2:3,2:4) 3 4 5
4 5 6
Deleting a Row or a Column in a Matrix
We can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that
row or column. Basically, [] denotes an empty array.
For example, let us delete the fourth row of a –
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 a=
8]; 1 2 3 4 5
a( 4 , : ) = [] 2 3 4 5 6
3 4 5 6 7
Next, let us delete the fifth column of a –
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 a=
8]; 1 2 3 4
a(: , 5)=[] 2 3 4 5
3 4 5 6
One matrix may be used to define another matrix, e.g.,
A = [4, 5, 6];
B = [1, 2, 3 ,4 ,5 ,6];
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.
>> a = [ 1 2 3 ; 4 5 6; 7 8 9]; new_mat =
>> new_mat = a([2,3,2,3],:) 4 5 6
7 8 9
4 5 6
7 8 9
Matrix Operations
Operation Matlab code Output
Matrix addition >>a = [ 1 2 3 ; 4 5 6; 7 8 9]; c=
>>b = [ 7 5 6 ; 2 0 8; 5 7 1];
>>c = a + b 8 7 9
6 5 14
12 15 10
Matrix subtraction >>a = [ 1 2 3 ; 4 5 6; 7 8 9]; d=
>>b = [ 7 5 6 ; 2 0 8; 5 7 1];
>>d = a - b -6 -3 -3
2 5 -2
2 1 8
Division(/) a = [ 1 2 3 ; 4 5 6; 7 8 9]; c=
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a / b % a*inv(b) -0.52542 0.68644 0.66102
-0.42373 0.94068 1.01695
-0.32203 1.19492 1.37288
Division(\) a = [ 1 2 3 ; 4 5 6; 7 8 9]; d=
b = [ 7 5 6 ; 2 0 8; 5 7 1];
d = a \ b % inv(a)*b -3.27778 -1.05556 -4.86111
-0.11111 0.11111 -0.27778
3.05556 1.27778 4.30556
Scalar Operations of Matrices a = [ 10 12 23 ; 14 8 6; 27 8 9]; c=
b = 2;
When you add, subtract, c=a+b 12 14 25
multiply or divide a matrix by a d=a-b 16 10 8
number, this is called the scalar e=a*b
operation. f=a/b 29 10 11
d=
Scalar operations produce a new
8 10 21
matrix with same number of
rows and columns with each 12 6 4
element of the original matrix 25 6 7
added to, subtracted from,
multiplied by or divided by the .....
number.
Transpose of a Matrix a = [ 10 12 23 ; 14 8 6; 27 8 9] a=
b = a'
10 12 23
14 8 6
27 8 9
b=
10 14 27
12 8 8
23 6 9
Horizontal concatenation a = [ 10 12 23 ; 14 8 6; 27 8 9] a=
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b] 10 12 23
14 8 6
27 8 9
b=
12 31 45
8 0 -9
45 2 11
c=
10 12 23 12 31 45
14 8 6 8 0 -9
27 8 9 45 2 11
Vertical concatenation a = [ 10 12 23 ; 14 8 6; 27 8 9] a=
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
d = [a; b] 10 12 23
14 8 6
27 8 9
b=
12 31 45
8 0 -9
45 2 11
d=
10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11
Matrix Multiplication a = [ 1 2 3; 2 3 4; 1 2 5] a=
b = [ 2 1 3 ; 5 0 -2; 2 3 -1]
prod = a * b 1 2 3
2 3 4
1 2 5
b=
2 1 3
5 0 -2
2 3 -1
prod =
18 10 -4
27 14 -4
22 16 -6
Determinant of a Matrix a = [ 1 2 3; 2 3 4; 1 2 5] a=
det(a)
1 2 3
2 3 4
1 2 5
ans = -2
Inverse of a Matrix a = [ 1 2 3; 2 3 4; 1 2 5] a=
inv(a)
1 2 3
2 3 4
1 2 5
ans =
-3.5000 2.0000 0.5000
3.0000 -1.0000 -1.0000
-0.5000 0 0.5000
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays,
and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write –
If you want to specify an increment value other than one, for example –
>> x = 20: 5: 50 x = 20 25 30 35 40 45 50
>> 0:pi/8:pi ans = 0 355/904 355/452 1065/904 355/226 1775/904
1065/452 2485/904 355/113
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
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
is all the elements of A, regarded as a single column. On the left side of an assignment
A(:) statement, A(:) fills A, preserving its shape from before. In this case, the right side
must contain the same number of elements as A.
Example
>> A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A=
A(:,2) % second column of A
A(:,2:3) % second and third column of A 1 2 3 4
A(2:3,2:3) % second and third rows and second 4 5 6 7
and third columns 7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9