Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70

MATLAB – Overview-0

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: Why it is called MATLAB?


MATLAB was originally developed to be a matrix laboratory
 In its present form it has been greatly expanded to include many other features, but still maintains
inherent matrix and vector based arithmetic at its core
 The basic data structure of MATLAB is the matrix

– A matrix with a single row is also known as a row vector


– A matrix with a single column is also known as a column vector
– A matrix with just one row and one column (a single element) is simply a scalar

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

Working directly in Command Window and working in Editor


function ave = rabiul(x)
ave = sum(x(:))/numel(x);
end

function name must be same to the script name.


You must add the directory to the search path.

Introduction to the layout


Simple Analysis
• The first group of data analysis functions to consider finds maximums, minimums, sums, and products
of vectors or columns of matrices
Example:
>> x = 0:10;
>> x_max = max(x); x_min = min(x);

>> x_sum = sum(x); x_prod = prod(x)


>> [x_max x_min x_sum x_prod]

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

[output1 output2]= functionname (input1, input2)

The Difference Between Functions and Scripts

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

Type a valid expression, for example,

>> 5 + 5 ans = 10

And press ENTER

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result
returned is −

Let us take up few more examples –

>> 3 ^ 2 % 3 raised to the power of 2 ans = 9

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,

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,

>> 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

 Use of Semicolon (;)

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.

 Saving Your Work

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,

>> save myfile

You can reload the file anytime later using the load command.

>> load myfile

Comma, semicolon and space

 A comma or a blank is used to separate elements in the same row.


 A semicolon is used to separate rows
>> B = [23 35.3] % blank space separated >> B = [23, 35.3] % comma separated

B= B=

23.0000 35.3000 23.0000 35.3000

 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

Variable names in MATLAB


 Must be begin with a letter
 May contain digits and the underscore character
 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.
 In MATLAB environment, every variable is an array or matrix.

Type Description Example Output

char Character array  C = 'Hello, world' C=


 A='strval' 'Hello, world'
 A=['s' 't' 'r' 'v' 'a' 'l']

complex Complex data. Cast z = complex(2,6) z=


function takes real and 2.0000 + 6.0000i
imaginary components
double Double-precision x = 10; x=
floating point 10
int8, int16, int32, int64 Signed integer y = int8(10); y=
int8
10
logical Boolean true or false  L = logical(A) L=
 A=logical([1,0,1]) logical
 A=[true, false, true] 1

single Single-precision y = single(10); y=


floating point single
10
struct Structure s.b = {'A','B','C'} s=
struct with fields:
student(2).name='Joe' a: 1
student(2).class=9 b: {'A' 'B' 'C'}
student(2).cgpa=3.7
uint8, uint16, uint32, uint64 Unsigned integer y = uint8(10); y=
uint8
10

Examples:

You can assign variables in a simple way. For example,

>> x = 3 % defining x and initializing it with a value

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,

>> x = sqrt(16) % defining x and initializing it with an expression

MATLAB will execute the above statement and return the following result −

x=4

Please note that −

 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

You can use this variable ans −

>>sqrt(78);
>>9876/ans

MATLAB will execute the above statement and return the following result −

ans = 1118.2

Let's look at another example −

>>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

 I have forgotten the Variables!

The who command displays all the variable names you have used.

>>who

MATLAB will execute the above statement and return the following result −

>> who

Your variables are:

ans p q

The whos command displays little more about the variables −

 Variables currently in memory


 Type of each variables
 Memory allocated to each variable
 Whether they are complex variables or not

>> whos
Name Size Bytes Class Attributes

ans 1x6 6 logical


p 1x6 48 double
q 1x6 48 double

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

% peacefully and unobtrusively

 Long Assignments

Long assignments can be extended to another line by using an ellipses (...). For example,

>> M = [.1, .2, .3, .4, .5, ...

.6, .7, .8, .9, 1.0]

M=

0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000

Output Display/Print Formatting


Globally the display format for the command window can be changed by:
(1) 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

(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

 The format Command

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

The format long command displays 16 digits after decimal.

For example −

>> format long


>> x = 7 + 10/3 + 5 ^ 1.2

x=
17.231981640639408

Another example,

>> format short


>> x = 7 + 10/3 + 5 ^ 1.2

x=
17.2320

The format bank command rounds numbers to two decimal places. For example,

>> format bank


>> x = 7 + 10/3 + 5 ^ 1.2

x=
17.23

MATLAB displays large numbers using exponential notation.

The format short e command allows displaying in exponential form with four decimal places plus the
exponent.

For example,

>> format short e


>> x = 7 + 10/3 + 5 ^ 1.2

x=
1.7232e+01

The format long e command allows displaying in exponential form with four decimal places plus the
exponent. For example,

>> format long e


>> x = 7 + 10/3 + 5 ^ 1.2

x=

1.723198164063941e+01

The format rat command gives the closest rational expression resulting from a calculation. For example,

>> format rat


>> x = 7 + 10/3 + 5 ^ 1.2

x=
7651/444
– Selecting displays formats from the command window pull down menus, e.g.,

Special Variables and Constants

MATLAB supports the following special variables and constants −

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i,j The imaginary unit √-1.


Inf Infinity.

NaN Undefined numerical result (not a number).

pi The number π

 Save and load variables


Save and load data

1. Data File Commands


 Data file commands are used to save (save filename vatiables you want to save) and load files
(load filename) in either standard ASCII text or the more compact MATLAB binary format
which uses the *.mat extension
 The binary .mat format is useful for files which will be used with MATLAB, while the ASCII
format is useful when working with other programs, or sharing data with others who may not
have MATLAB

>> x = 0:5; Name Size Bytes Class Attributes


>> y = rand(size(x)); x 1x6 48 double
>> save mat_data x y; % creates the file y 1x6 48 double
mat_data.mat
>> save mat_data.dat x y /ascii; % creates the text
file
>> clear %To verify that these files are valid we
first clear the MATLAB work space using the
command
>> load mat_data % Next we load the .mat file
back into the work space
>> whos
>> x
>> y
Special Values and Matrices
To make life easier, MATLAB comes with several predefined values and matrix generators
 pi represents in MATLAB floating point precision, e.g.,
>> pi
ans = 3.1416
 i, j represents the value

>> i

ans =

0.0 + 1.0000i

>> j

ans =

0.0000 + 1.0000i

 Inf is the MATLAB notation for infinity, i.e., 1/0

>> Inf
ans =

Inf

 nan is the MATLAB representation for not-a-number; often a result of a 0/0 operation

>> nan
ans =

NaN

 clock displays the current time, e.g.,

>> clock

ans =

1.0e+03 *

2.0230 0.0110 0.0170 0.0100 0.0130 0.0029

>> help clock

>> 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

 A matrix of zeros can be generated with


 MATLAB – Commands--3

 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

clc Clears command window.

clear Removes variables from memory.

exist Checks for existence of file or variable.

global Declares variables to be global.

help Searches for a help topic.

lookfor Searches help entries for a keyword.

quit Stops MATLAB.

who Lists current variables.

whos Lists current variables (long display).


 Commands for Working with the System
 MATLAB provides various useful commands for working with the system, like saving the
current work in the workspace as a file and loading the file later.
 It also provides various commands for other system-related activities like, displaying date, listing
files in the directory, displaying current directory, etc.
 The following table displays some commonly used system-related commands −
Command Purpose

cd Changes current directory.


date Displays current date.

delete Deletes a file.

diary Switches on/off diary file recording.

dir Lists all files in current directory.

load Loads workspace variables from a file.

path Displays search path.

pwd Displays current directory.

save Saves workspace variables in a file.

type Displays contents of a file.

what Lists all MATLAB files in the current directory.

wklread Reads .wk1 spreadsheet file.


 Input and Output Commands
 MATLAB provides the following input and output related commands −
Command Purpose

disp Displays contents of an array or string.

fscanf Read formatted data from a file.

format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.

; Suppresses screen printing.


 The fscanf and fprintf commands behave like C scanf and printf functions. They support the
following format codes −
Format Code Purpose

%s Format as a string.

%d Format as an integer.
%f Format as a floating point value.

%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.

\n Insert a new line in the output string.

\t Insert a tab in the output string.


 The format function has the following forms used for numeric display −
Format Function Display up to

format short Four decimal digits (default).

format long 16 decimal digits.

format short e Five digits plus exponent.

format long e 16 digits plus exponents.

format bank Two decimal digits.

format + Positive, negative, or zero.

format rat Rational approximation.

format compact Suppresses some line feeds.

format loose Resets to less compact display mode.


 Vector, Matrix and Array Commands
 The following table shows various commands used for working with arrays, matrices and vectors

Command Purpose

cat Concatenates arrays.

find Finds indices of nonzero elements.

length Computes number of elements.

linspace Creates regularly spaced vector.

logspace Creates logarithmically spaced vector.


max Returns largest element.

min Returns smallest element.

prod Product of each column.

reshape Changes size.

size Computes array size.

sort Sorts each column.

sum Sums each column.

eye Creates an identity matrix.

ones Creates an array of ones.

zeros Creates an array of zeros.

cross Computes matrix cross products.

dot Computes matrix dot products.

det Computes determinant of an array.

inv Computes inverse of a matrix.

pinv Computes pseudoinverse of a matrix.

rank Computes rank of a matrix.

rref Computes reduced row echelon form.

cell Creates cell array.

celldisp Displays cell array.

cellplot Displays graphical representation of cell array.

num2cell Converts numeric array to cell array.

deal Matches input and output lists.

iscell Identifies cell array.


 Plotting Commands
 MATLAB provides numerous commands for plotting graphs. The following table shows some of
the commonly used commands for plotting −
Command Purpose

axis Sets axis limits.

fplot Intelligent plotting of functions.

grid Displays gridlines.

plot Generates xy plot.

print Prints plot or saves plot to a file.

title Puts text at top of plot.

xlabel Adds text label to x-axis.

ylabel Adds text label to y-axis.

axes Creates axes objects.

close Closes the current plot.

close all Closes all plots.

figure Opens a new figure window.

gtext Enables label placement by mouse.

hold Freezes current plot.

legend Legend placement by mouse.

refresh Redraws current figure window.

set Specifies properties of objects such as axes.

subplot Creates plots in subwindows.

text Places string in figure.

bar Creates bar chart.

loglog Creates log-log plot.


polar Creates polar plot.

semilogx Creates semilog plot. (logarithmic abscissa).

semilogy Creates semilog plot. (logarithmic ordinate).

stairs Creates stairs plot.

stem Creates stem plot.


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

Creating and Running Script File


To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways −
 Using the command prompt
 Using the IDE
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 (>>) −
mkdir progs % create directory progs under default directory
chdir progs % changing the current directory to progs
edit prog1.m % creating an m file named prog1.m
chdir .. % back to previous folder
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.
Type the following code in the editor −
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;

Total = NoOfStudents + TeachingStaff ...


+ NonTeachingStaff;
disp(Total);
After creating and saving the file, you can run it in two ways −
 Clicking the Run button on the editor window or
 Just typing the filename (without extension) in the command prompt: >> prog1
The command window prompt displays the result −
6170
Example
Create a script file, and type the following code −
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
MATLAB - Data Types-5

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

char Convert to character array (string)

int2str Convert integer data to string

mat2str Convert matrix to string

num2str Convert number to string

str2double Convert string to double-precision value

str2num Convert string to number

native2unicode Convert numeric bytes to Unicode characters

unicode2native Convert Unicode characters to numeric bytes

base2dec Convert base N number string to decimal number

bin2dec Convert binary number string to decimal number

dec2base Convert decimal to base N number in string

dec2bin Convert decimal to binary number in string

dec2hex Convert decimal to hexadecimal number in string

hex2dec Convert hexadecimal number string to decimal number

hex2num Convert hexadecimal number string to double-precision number

num2hex Convert singles and doubles to IEEE hexadecimal strings

cell2mat Convert cell array to numeric array

cell2struct Convert cell array to structure array

cellstr Create cell array of strings from character array

mat2cell Convert array to cell array with potentially different sized cells

num2cell Convert array to cell array with consistently sized cells

struct2cell Convert structure to cell array


 Determination of Data Types
MATLAB provides various functions for identifying data type of a variable.
Following table provides the functions for determining the data type of a variable −
Function Purpose

is Detect state

isa Determine if input is object of specified class

iscell Determine whether input is cell array

iscellstr Determine whether input is cell array of strings

ischar Determine whether item is character array

isfield Determine whether input is structure array field

isfloat Determine if input is floating-point array

ishghandle True for Handle Graphics object handles

isinteger Determine if input is integer array

isjava Determine if input is Java object

islogical Determine if input is logical array

isnumeric Determine if input is numeric array

isobject Determine if input is MATLAB object

isreal Check if input is real array

isscalar Determine whether input is scalar

isstr Determine whether input is character array

isstruct Determine whether input is structure array

isvector Determine whether input is vector

class Determine class of object

validateattributes Check validity of array

whos List variables in workspace, with sizes and types


Example
Create a script file with the following code −

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 −

Sr.No. Operator Description

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.

3 * Matrix multiplication. C = A*B is the linear algebraic product of the matrices A


and B. More precisely,
For non-scalar A and B, the number of columns of A must be equal to the number
of rows of B. A scalar can multiply a matrix of any size.

Array multiplication. A.*B is the element-by-element product of the arrays A and


4 .*
B. A and B must have the same size, unless one of them is a scalar.

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.

Backslash or matrix left division, Left-division operator.. If A is a square matrix,


A\B is roughly the same as inv(A)*B, except it is computed in a different way. If A
7 \ is an n-by-n matrix and B is a column vector with n components, or a matrix with
several such columns, then X = A\B is the solution to the equation AX = B. A
warning message is displayed if A is badly scaled or nearly singular.

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.

Matrix power, matrix exponentiation operator.. X^p is X to the power p, if p is a


scalar. If p is an integer, the power is computed by repeated squaring. If the integer
9 ^
is negative, X is inverted first. For other values of p, the calculation involves
eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V.

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.

Scalar and Array Operations


Computations in MATLAB typically require wide variety of arithmetic computations between scalars,
vectors, and matrices.
1. Scalar Operations
% Assign constants to a and b:

>> 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 % Scalar operating on a vector B = 2 6 10 14

>> 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 −

Sr.No. Operator Description

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 −
 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

bitand(a, b) Bit-wise AND of integers a and b

bitcmp(a) Bit-wise complement of a

bitget(a,pos) Get bit at specified position pos, in the integer array a

bitor(a, b) Bit-wise OR of integers a and b

bitset(a, pos) Set bit at specific location pos of a

Returns a shifted to the left by k bits, equivalent to multiplying by 2k.


Negative values of k correspond to shifting bits right or dividing by 2|
bitshift(a, k) k|
and rounding to the nearest integer towards negative infinite. Any
overflow bits are truncated.

bitxor(a, b) Bit-wise XOR of integers a and b

swapbytes Swap byte ordering


 Set Operations
MATLAB provides various functions for set operations, like union, intersection and testing for set
membership, etc.
The following table shows some commonly used set operations −

Sr.No. Function & Description

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

 Commonly used Operators and Special Characters


MATLAB supports the following commonly used operators and special characters −
Operator Purpose

Colon; generates regularly spaced elements and represents an entire


:
row or column.

Parentheses; encloses function arguments and array indices; overrides


()
precedence.

[] Brackets; enclosures array elements.

. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and specifies formatting.

_ Quote sign and transpose operator.

._ Nonconjugated transpose operator.

= 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

– Here we use to generate row and column slices of a matrix

>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]

A=

1 2 3
4 5 6
7 8 9

>> A_col2 = A(:,2) % Span all rows with the column

A_col2 =

2
5
8

>> A_11 = A(2,2) % Produces the scalar A_11 = 5

A_11 =

 We can combine the techniques to extract a submatrix of A


>> A_sub = A(2:3,2:3) % Extract a sub matrix % consisting of rows 2-3 and % columns 2-3
A_sub =
5 6
8 9

 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)

>> A = [0, 1, 2, 3, 4];


>> B = [0, 1, 4, 9, 16];
>> C = [0, 1, 8, 27, 64];
>> [A' B' C'] % Display in side-by-side columns:

ans =

0 0 0
1 1 1
2 4 8
3 9 27
4 16 64

MATLAB - Decision Making-7

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 ... end statement


1
An if ... end statement consists of a boolean expression followed by one or more statements.

if...else...end statement
2 An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

If... elseif...elseif...else...end statements


3 An if statement can be followed by one (or more) optional elseif... and an else statement,
which is very useful to test various conditions.

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.

nested switch statements


6
You can use one switch statement inside another switch statement(s).
 if ... end statement

The syntax of an if statement in MATLAB is –

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

a = 10; a is less than 20


% check the condition using if statement value of a is : 10
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);

>> x=10; Hello world!


>> if x < 15
fprintf('Hello world!\n')
end

 MATLAB - if...else...end Statement


An if statement can be followed by an optional else statement, which executes when the expression is
false.
Syntax

The syntax of an if...else statement in MATLAB is –

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

a = 100; a is not less than 20


% check the boolean condition value of a is : 100
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
else
% if condition is false then print the following
fprintf('a is not less than 20\n' );
end
fprintf('value of a is : %d\n', a);

>> x=10; Correct


>> if x < 15
fprintf('Correct\n')
else
fprintf('Wrong\n')
end

 MATLAB - if...elseif...elseif...else...end Statements

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)>

elseif <expression 2>


% Executes when the boolean expression 2 is true
<statement(s)>

Elseif <expression 3>


% Executes when the boolean expression 3 is true
<statement(s)>

else
% executes when the none of the above condition is true
<statement(s)>
end

Example

a = 100; None of the values are matching


%check the boolean condition Exact value of a is: 100
if a == 10
% if condition is true then print the following
fprintf('Value of a is 10\n' );
elseif( a == 20 )
% if else if condition is true
fprintf('Value of a is 20\n' );
elseif a == 30
% if else if condition is true
fprintf('Value of a is 30\n' );
else
% if none of the conditions is true '
fprintf('None of the values are matching\n');
fprintf('Exact value of a is: %d\n', a );
end

 MATLAB - The Nested if Statements

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

The syntax for a nested if statement is as follows –

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

a = 100; Value of a is 100 and b is 200


b = 200; Exact value of a is : 100
% check the boolean condition Exact value of b is : 200
if( a == 100 )

% if condition is true then check the following


if( b == 200 )

% if condition is true then print the


following
fprintf('Value of a is 100 and b is 200\n' );
end

end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );

 MATLAB - The switch Statement

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

The syntax of switch statement in MATLAB is –

switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end

Example

Create a script file and type the following code in it –

grade = 'B'; Well done


switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end

 MATLAB - The Nested switch Statements

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

The syntax for a nested switch statement is as follows −


switch(ch1)
case 'A'
fprintf('This A is part of outer switch');
switch(ch2)
case 'A'
fprintf('This A is part of inner switch' );

case 'B'
fprintf('This B is part of inner switch' );
end
case 'B'
fprintf('This B is part of outer switch' );
end

Example

a = 100; This is part of outer switch 100


b = 200; This is part of inner switch 100
switch(a) Exact value of a is : 100
case 100
Exact value of b is : 200
fprintf('This is part of outer switch %d\n', a );
switch(b)
case 200
fprintf('This is part of inner switch %d\n', a
);
end
end

fprintf('Exact value of a is : %d\n', a );


fprintf('Exact value of b is : %d\n', b );

MATLAB - Loop Types-8

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.

 MATLAB - The while Loop

The while loop repeatedly executes statements while condition is true.


Syntax
The syntax of a while loop in MATLAB is −
while <expression>
<statements>
end
The while loop repeatedly executes program statement(s) as long as the expression remains true.
An expression is true when the result is nonempty and contains all nonzero elements (logical or real
numeric). Otherwise, the expression is false.
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
end value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 MATLAB - The for 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 - The Nested Loops

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

 Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
MATLAB supports the following control statements.
Sr.No. Control Statement & Description

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 - The break Statement

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

 MATLAB - continue Statement

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

 Special Arrays in MATLAB


In this section, we will discuss some functions that create some special arrays. For all these functions, a
single argument creates a square array, double arguments create rectangular array.
 The zeros() function creates an array of all zeros −
For example –
>> zeros(4)
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
 The ones() function creates an array of all ones −
For example –
>> ones(2,2) ans =
1 1
1 1
 The eye() function creates an identity matrix.
For example –
>> eye(4,4) 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 –
>> rand(5) ans =
664/815 694/7115 589/3737 689/4856 3581/5461
1298/1433 408/1465 6271/6461 407/965 489/13693
751/5914 1324/2421 581/607 1065/1163 439/517
717/785 338/353 614/1265 61/77 283/303
1493/2361 687/712 1142/1427 1966/2049 1481/2182
 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.
>> magic(4)
ans =

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) =

979/1292 1193/6969 243/5263


541/728 1016/1439 701/7217
1645/4194 128/4021 681/827
1406/2145 18/65 954/1373

b(:,:,2) =

293/924 1469/3850 1268/2589


1069/1125 111/145 954/2141
259/7519 497/625 561/868
573/1306 242/1295 659/929

 We can also use the cat() function to build multidimensional arrays. It concatenates a list of
arrays along a specified dimension −

Syntax for the cat() function is −


B = cat(dim, A1, A2...)
Where,
 B is the new array created
 A1, A2, ... are the arrays to be concatenated
 dim is the dimension along which to concatenate the arrays
Example
Create a script file and type the following code into it –

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

length Length of vector or largest array dimension

ndims Number of array dimensions

numel Number of array elements


size Array dimensions

iscolumn Determines whether input is column vector

isempty Determines whether array is empty

ismatrix Determines whether input is matrix

isrow Determines whether input is row vector

isscalar Determines whether input is scalar

isvector Determines whether input is vector

blkdiag Constructs block diagonal matrix from input arguments

circshift Shifts array circularly

ctranspose Complex conjugate transpose

diag Diagonal matrices and diagonals of matrix

flipdim Flips array along specified dimension

fliplr Flips matrix from left to right

flipud Flips matrix up to down

ipermute Inverses permute dimensions of N-D array

permute Rearranges dimensions of N-D array

repmat Replicates and tile array

reshape Reshapes array

rot90 Rotates matrix 90 degrees

shiftdim Shifts dimensions

issorted Determines whether set elements are in sorted order

sort Sorts array elements in ascending or descending order

sortrows Sorts rows in ascending order

squeeze Removes singleton dimensions


transpose Transpose

vectorize Vectorizes expression


Examples
The following examples illustrate some of the functions mentioned above.
 Length, Dimension and Number of elements −
Create a script file and type the following code into it –

x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9]; ans = 8


length(x) % length of x vector ans = 4
y = rand(3, 4, 5, 2); ans = 23
ndims(y) % no of dimensions in array y
s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];
numel(s) % no of elements in s

 Circular Shifting of the Array Elements −


Create a script file and type the following code into it –
a = [1 2 3; 4 5 6; 7 8 9] % the original array a a=
b = circshift(a,1) % circular shift first 1 2 3
dimension values down by 1. 4 5 6
c = circshift(a,[1 -1]) % circular shift first 7 8 9
dimension values % down by 1
% and second dimension values b=
to the left % by 1. 7 8 9
1 2 3
4 5 6

c=
8 9 7
2 3 1
5 6 4

 Sorting Arrays
Create a script file and type the following code into it –

v = [ 23 45 12 9 5 0 19 17] % horizontal vector v=


sort(v) % sorting v 23 45 12 9 5 0 19 17
m = [2 6 4; 5 3 9; 2 0 1] % two dimensional ans =
array 0 5 9 12 17 19 23 45
sort(m, 1) % sorting m along the row m=
sort(m, 2) % sorting m along the 2 6 4
column 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
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

>> A={'name', 12} A=


1×2 cell array
{'name'} {[12]}
>> A={'john','joe'} A=
1×2 cell array
{'john'} {'joe'}

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 –

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 ans = Blue


4 5}; ans = Green
c{1, 2:4} ans = Yellow

MATLAB – Vectors-10

A vector is a one-dimensional array of numbers.


MATLAB allows creating two types of vectors −
 Row vectors
 Column vectors
Row Vectors
A matrix with a single row is also known as a row vector.
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to
delimit the elements.
>> r = [7 8 9 10 11] r=
7 8 9 10 11
>> B = [23, 35.3] % A 1x2 matrix B = 23.0000 35.3000

>> 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

 Vectors with Uniformly Spaced Elements

>> v = [1: 5: 20] v= 1 6 11 16

 Referencing the Elements of a Vector


You can reference one or more of the elements of a vector in several ways. The i th component of a vector
v is referred as v(i). For example –
>> v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements ans =
>> v(3) 3

When you reference a vector with a colon, such as v(:), all the components of the vector are listed.

>> v = [ 1; 2; 3; 4; 5; 6];% creating a column vector of 6 ans =


elements
v(:) 1
2
3
4
5
6

 MATLAB allows you to select a range of elements from a vector.


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.

>> rv = [1 2 3 4 5 6 7 8 9]; sub_rv =


>> sub_rv = rv(3:7)
3 4 5 6 7

 Vector Operations

Operation Matlab code Output


Vectors addition A = [7, 11, 15, 23, 9]; 9 16 28 39 29
B = [2, 5, 13, 16, 20];
C = A + B;
disp(C);
Vectors subtraction A = [7, 11, 15, 23, 9]; 5 6 2 7 -11
B = [2, 5, 13, 16, 20];
D = A - B;
disp(D);
Scalar Multiplication of Vectors v = [ 12 34 10 8]; m=
m=5*v
60 170 50 40

Transpose of a Vector r=[1234] r=


tr = r'
1
2
3
4
r=
1 2 3 4

Appending Vectors r1 = [ 1 2 3 4 ]; r=1 2 3 4


r2 = [5 6 7 8 ];
r = [r1,r2] 5 6 7 8
rMat = [r1;r2]
rMat =
1 2 3 4
5 6 7 8

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

 MATLAB was originally developed to be a matrix laboratory.


 In its present form it has been greatly expanded to include many other features, but still maintains
inherent matrix and vector based arithmetic at its core.
 The basic data structure of MATLAB is the matrix.

A matrix is a two-dimensional array of numbers.


In MATLAB, we 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.
>> A=[2 3 ; 4 5 ; 6 7] A=
2 3
4 5
6 7
>> B=[[2;4;6] , [3 ;5;7]] B=
2 3
4 5
6 7
>> a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8] a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

 Referencing the Elements of a Matrix


To reference an element in the mth row and nth column of a matrix A, we write –
A(m, n);

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, A]; % creates

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

MATLAB - Colon Notation-12

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 –

>> x = 1:5 x=1 2 3 4 5

 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(:,j) is the jth column of A.

A(i,:) is the ith row of A.

A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.

A(j:k) is A(j), A(j+1),...,A(k).

A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k) is the kth page of three-dimensional array A.

is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2),


A(i,j,k,:)
A(i,j,k,3), and so on.

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

You might also like