You are on page 1of 207

WELCOME TO

BASICS OF MATLAB
By:
Prof. Abhijit V. Chitre
Prof. Pravin G. Gawande
Department of Electronics and Telecommunications Engineering
Vishwakarma Institute of Information Technology, PUNE
Getting Started with
MATLAB
What Is MATLAB?
The name MATLAB stands for matrix laboratory

MATLAB is a high-performance language for


technical computing.

It integrates computation, visualization, and


programming in an easy-to use environment where
problems and solutions are expressed in familiar
mathematical notation.
The Advantages of MATLAB for
technical programming
1. Ease of use
2. Platform Independence
3. Pre-Defined functions
4. Device independent plotting
5. Graphical user interface
MATLAB has evolved over a period of years with
input from many users.

In university environments, it is the standard


instructional tool for introductory and advanced
courses in mathematics, engineering, and science.

In industry, MATLAB is tool of choice for high


productivity research, development and analysis
MATLAB features a family of add-on application-specific
solutions called toolboxes.

Very important to most users of MATLAB,

toolboxes allow you to learn and apply specialized technology.

Toolboxes are comprehensive collections of MATLAB


functions (M-files) that extend the MATLAB environment to
solve particular classes of problems.

Areas in which toolboxes are available include signal


processing, control systems, neural networks, fuzzy logic,
wavelets, simulation, and many others.
Disadvantages of MATLAB
It is an interpreted language and therefore can
execute more slowly than compiled language

This problem can be avoided by properly


structuring the MATLAB program

The second disadvantage is cost: a full copy of


MATLAB is five to ten times more expensive than
a conventional C or Fortran.
The MATLAB System

The MATLAB system consists of five main parts:

Development Environment.
The MATLAB Mathematical Function Library.
The MATLAB Language.
Graphics.
The MATLAB Application Program Interface
(API).
Development Environment.

This is the set of tools and facilities that help you use
MATLAB functions and files.
Many of these tools are graphical user interfaces.
It includes the MATLAB desktop and Command
Window, a command history, an editor and debugger,
and browsers for viewing help, the workspace, files,
and the search path.
The MATLAB Mathematical Function
Library.

This is a vast collection of computational


algorithms ranging from elementary functions like
sum, sine, cosine, and complex arithmetic, to more
sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier
transforms.
The MATLAB Language.

This is a high-level matrix/array language with


control flow statements, functions, data structures,
input/output, and object-oriented programming
features.

It allows both “programming in the small” to


rapidly create quick and dirty throw-away
programs,

and “programming in the large” to create


complete large and complex application programs
Graphics.

MATLAB has extensive facilities for displaying


vectors and matrices as graphs,
as well as annotating and printing these graphs.
It includes high-level functions for two-
dimensional and three-dimensional data
visualization, image processing, animation, and
presentation graphics.
The MATLAB Application Program
Interface (API).

This is a library that allows you to write C and


Fortran programs that interact with MATLAB.
It includes facilities for calling routines from
MATLAB (dynamic linking), calling MATLAB as
a computational engine, and for reading and
writing MAT-files.
First Steps in MATLAB

Starting MATLAB
To run MATLAB on a PC double-click on the MATLAB icon.
To run MATLAB on a UNIX system, type MATLAB at the
prompt.

You get MATLAB to do things for you by typing in


commands. MATLAB prompts you with two greater-than
signs (>>) when it is ready to accept a command from you.

To end a MATLAB session type quit or exit at the MATLAB


prompt.
Development Environment
MATLAB Desktop
Desktop Tools
•“Command Window”
•“Command History”
•“Start Button and Launch Pad”
•“Help Browser”
•“Current Directory Browser”
•“Workspace Browser”
•“Array Editor”
•“Editor/Debugger”
•“Profiler”
First Steps in MATLAB

When starting MATLAB you should see a


message:

To get started, type one of these commands: helpwin,


helpdesk, or demo
>>
First Steps in MATLAB
When starting MATLAB you should see a message:

To get started, type one of these commands: helpwin,


helpdesk, or demo
>>

The various forms of help available are :

Helpwin  Opens a MATLAB help GUI

helpdesk  Opens a hypertext help browser

demo  Starts the MATLAB demonstration


First Steps in MATLAB
You can learn how to use any MATLAB command by typing help
followed by the name of the command,
for example, help sin.

You can also use the lookfor command, which searches the help
entries for all MATLAB commands for a particular word.
For example, if you want to know which MATLAB functions to use
for spectral analysis,
you could type lookfor spectrum.
MATLAB responds with the names of the commands that have the
searched word in the first line of the help entry.

You can search the entire help entry for all MATLAB commands
by typing lookfor -all keyword .

To break search press ctrl c keys


First Steps
To get MATLAB to work out 1 + 1, type the following at the prompt:
>> 1+1
MATLAB responds with
ans =
2
The answer to the typed command is given the name ans. In fact ans
is now a variable that you can use again. For example you can type
ans*ans to check that 2 X 2 = 4:

>> ans*ans
ans =
4
MATLAB has updated the value of ans to be 4.
First Steps
The spacing of operators in formulas does not matter.
The following formulas both give the same answer:

1+3 * 2-1 / 2*4


1+3*2-1/2*4

The order of operations is made clearer to readers of your


MATLAB code if you type carefully:

1 + 3*2 - (1/2)*4
First Steps DATA TYPES
here are many different types of data that you can work with in MATLAB.
You can build matrices and arrays of floating-point and integer data, characters and
strings, logical true and false states, etc. Two of the MATLAB data types, structures
and cell arrays, provide a way to store dissimilar types of data in the same array.
You can also develop your own data types using MATLAB classes.
There are 15 fundamental data types in MATLAB. Each of these data types is in the
form of a matrix or array. This matrix or array is a minimum of 0-by-0 in size and
can grow to an n-dimensional array of any size.
All of the fundamental data types are shown in lowercase, plain nonitalic text in the
diagram below.
First Steps DATA TYPES
First Steps DATA TYPES
Integers MATLAB has four signed and four unsigned integer data
types. Signed types enable you to work with negative integers as well
as positive, but cannot represent as wide a range of numbers as the
unsigned types because one bit is used to designate a positive or
negative sign for the number. Unsigned types give you a wider range
of numbers, but these numbers can only be zero or positive.
First Steps DATA TYPES
Single-Precision Floating Point MATLAB constructs the single-
precision (or single) data type according to IEEE Standard 754 for
single precision. Any value stored as a single requires 32 bits,
formatted as shown in the table below:

Because MATLAB stores numbers of type single using32 bits, they require
less memory than numbers of type double, which use 64 bits. However,
because they are stored with fewer bits, numbers of type single are
represented to less precision than numbers of type double.
First Steps DATA TYPES
Double-Precision Floating Point MATLAB constructs the double-
precision (or double) data type according to IEEE Standard 754 for
double precision. Any value stored as a double requires 64 bits,
formatted as shown in the table below:

Because MATLAB stores numbers of type single using32 bits, they require
less memory than numbers of type double, which use 64 bits. However,
because they are stored with fewer bits, numbers of type single are
represented to less precision than numbers of type double.
First Steps DATA TYPES
The logical data type represents a logical true or false state using the numbers 1 and 0, respectively. Certain MATLAB functions and operators return logical true or false to indicate whether a certain
condition was found to be true or not.
For example, the statement
(5 * 10) > 40 returns a logical true value.
Logical data does not have to be scalar; MATLAB supports arrays of logical values as well. For example, the following statement returns a vector of logicals indicating false for the first two elements
and true for the last three:
[30 40 50 60 70] > 40
ans =
0 0 1 1 1
First Steps DATA TYPES
The logical data
Creating a Logical Array One way of creating an array of logicals is to just enter a true or false value for each element. The true function returns logical one; the false function returns logical zero:

>> x = [true, true, false, true, false];

Logical Operations on an Array You can also perform some logical operation on an array that yields an array of logicals:
>> x = magic(4) >= 9
>> x =
1 0 0 1
0 1 1 0
1 0 0 1
0 1 1 0
First Steps VARIABLES

A and a are deferent variables.

The following are valid MATLAB variable assignments:


a=1
speed = 1500
BeamFormerOutput_Type1 = v*Q*v’
name = ’John Smith’

These are invalid assignments:


2for1 = ’yes’
first one = 1
First Steps VARIABLES
First Steps VARIABLES
To assign a variable without getting an echo from
MATLAB end the assignment with a semi-colon ;.

Try typing the following:


>>a = 2
>>b = 3;
>>c = a+b;
>>d = c/2;
>>d
>>who
>>whos
>>clear
First Steps VARIABLES
>>who

WHO List current variables.


WHO lists the variables in the current workspace.
First Steps VARIABLES
>>whos

WHOS List current variables, long form.


WHOS is a long form of WHO. It lists all the variables
in the current workspace, together with information
about their size, bytes, class, etc.
First Steps VARIABLES
>>clear

CLEAR Clear variables and functions from memory.


CLEAR removes all variables from the workspace.
CLEAR VARIABLES does the same thing.
CLEAR GLOBAL removes all global variables.
CLEAR FUNCTIONS removes all compiled M- and
MEX-functions.
CLEAR ALL removes all variables, globals, functions
and MEX links.
First Step
>>close

CLOSE Close figure.


CLOSE(H) closes the window with handle H.
CLOSE, by itself, closes the current figure window.
CLOSE ALL closes all the open figure windows.
CLOSE ALL HIDDEN closes hidden windows as well.
First Steps
>>clc

CLC Clear command window and homes the cursor.


First Steps VARIABLES
>>home

HOME Send the cursor home.


HOME moves the cursor to the upper left corner of the
window. When using the MATLAB desktop, it also
scrolls the visible text in the window up out of view; you
can use the scroll bar to see what was previously on the
screen.
Typing into MATLAB
Command Line Editing
If you make a mistake when entering a MATLAB command, you
do not have to type the whole line again. The arrow keys can be
used to save much typing:

If you finish editing in the middle of a line, you do not have to put the
cursor at the end of the line before pressing the return key; you can
press return when the cursor is anywhere on the command line.
Typing into MATLAB
Smart Recall

Repeated use of the key recalls earlier commands.

If you type the first few characters of a previous


command and then press the Key MATLAB will
recall the last command that began with those
characters. Subsequent use of will recall earlier
commands that began with those characters.
Typing into MATLAB
Long Lines
If you want to type a MATLAB command that is too long to fit on one
line, you can continue on to the next by ending with a space followed by
three full stops. For example, to type an expression with long variable
names:

Final_Answer = BigMatrix(row_indices,column_indices) + ...

Another_vector*SomethingElse;

Or to define a long text string:

Mission = [’DSTO’’s objective is to give advice that’ ...


’is professional, impartial and informed on the’ ...
’application of science and technology that is best’ ...
’suited to Australia’’s defence and security needs.’];
ARRAY ( MATRICES)
ARRAY( MATRICES)

The fundamental unit of data in any matlab program is


the array

ARRAY
VECTORS
ROW VECTOR Array with only one dimension
COLUMN VECTOR
MATRICES two or more dimensions
ARRAY( MATRICES)

Typing Matrices
To type a matrix into MATLAB you must

begin with a square bracket [


separate elements in a row with commas or spaces
use a semicolon ; to separate rows
end the matrix with another square bracket ].
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
ARRAY ( MATRICES)
The colon operator :

To generate a vector of equally-spaced elements MATLAB provides


the colon operator. Try the following commands:

1:5
0:2:10
0:.1:2*pi

The syntax x:y means roughly “generate the ordered set of numbers
from x to y with increment 1 between them.”

The syntax x:d:y means roughly “generate the ordered set of numbers
from x to y with increment d between them.”
Linspace :

To generate a vector of evenly spaced points between two end points,


you can use the function linspace(start,stop,npoints ):
>> x = linspace(0,1,10)
x=
Columns 1 through 7
0 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667
Columns 8 through 10
0.7778 0.8889 1.0000
generates 10 evenly spaced points from 0 to 1.

Typing linspace(start,stop ) will generate a vector of 100 points.


First Steps MATRICES

For example type :

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


MATLAB responds with
A=
1 2 3
4 5 6
7 8 9
CONCATENATING MATRICES

Concatenation
Concatenation is the process of joining small matrices to make bigger ones.

>> a=[1 2;1 2]


a=
1 2
1 2

>> b=[2 3;2 3]


b=
2 3
2 3
>> c=[a b]
c=

1 2 2 3
1 2 2 3
Useful Matrix Generators
MATLAB provides four easy ways to generate
certain simple matrices. These are :

zeros  a matrix filled with zeros


ones  a matrix filled with ones
Rand  a matrix with uniformly distributed
random elements
Randn  a matrix with normally distributed
random elements
Eye  identity matrix
Useful Matrix Generators
MATLAB provides four easy ways to generate certain simple
matrices. These are :

zeros  a matrix filled with zeros


ones  a matrix filled with ones
Rand  a matrix with uniformly distributed random elements
Randn  a matrix with normally distributed random elements
Eye  identity matrix

To tell MATLAB how big these matrices should be you give the
functions the number of rows and columns. For example:
>> a = zeros(2,3)
Useful Matrix Generators
MATLAB provides four easy ways to generate certain simple matrices.
These are :

zeros  a matrix filled with zeros


ones  a matrix filled with ones
Rand  a matrix with uniformly distributed random elements
Randn  a matrix with normally distributed random elements
Eye  identity matrix
To tell MATLAB how big these matrices should be you give the
functions the number of rows and columns. For example:
>> a = zeros(2,3)
a=
000
000
Useful Matrix Generators
>> b= ones(2,2)
b=
1 1
1 1
Useful Matrix Generators
>> b= ones(2,2)
b=
1 1
1 1
>> b = ones(2,2)/2
b=
0.5000 0.5000
0.5000 0.5000
Useful Matrix Generators
>> b= ones(2,2)
b=
1 1
1 1
>> b = ones(2,2)/2
b=
0.5000 0.5000
0.5000 0.5000
>> b = 5*ones(2,2)
b=
5 5
5 5
Useful Matrix Generators
>> u = rand(1,5)
u=
0.9218 0.7382 0.1763 0.4057 0.9355
Useful Matrix Generators
>> u = rand(1,5)
u=
0.9218 0.7382 0.1763 0.4057 0.9355

>> n = randn(5,5)
n=
-0.4326 1.1909 -0.1867 0.1139 0.2944
-1.6656 1.1892 0.7258 1.0668 -1.3362
0.1253 -0.0376 -0.5883 0.0593 0.7143
0.2877 0.3273 2.1832 -0.0956 1.6236
-1.1465 0.1746 -0.1364 -0.8323 -0.6918
Useful Matrix Generators

>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
Subscripting
Matrix Indexing
Accessing Single Elements
To reference a particular element in a matrix, specify its row and column
number using the following syntax, where A is the matrix variable. Always
specify the row first and column second:
A(row, column)
Subscripting
Matrix Indexing
Accessing Single Elements
To reference a particular element in a matrix, specify its row and column
number using the following syntax, where A is the matrix variable. Always
specify the row first and column second:
A(row, column)
For example, for a 4-by-4 magic square A,
A = magic(4)
A = 16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
you would access the element at row 4, column 2 with
A(4, 2)
ans = 14
Subscripting
Linear Indexing
With MATLAB, you can refer to the elements of a matrix with a single
subscript, A(k). MATLAB stores matrices and arrays not in the shape that
they appear when displayed in the MATLAB Command Window, but as a
single column of elements. This single column is composed of all of the
columns from the matrix, each appended to the last.
So, matrix A
A = [2 6 9; 4 2 8; 3 5 1]
A= 2 6 9
4 2 8
3 5 1
Subscripting
Linear Indexing
With MATLAB, you can refer to the elements of a matrix with a single subscript,
A(k). MATLAB stores matrices and arrays not in the shape that they appear when
displayed in the MATLAB Command Window, but as a single column of elements.
This single column is composed of all of the columns from the matrix, each
appended to the last.
So, matrix A
A = [2 6 9; 4 2 8; 3 5 1]
A= 2 6 9
4 2 8
3 5 1
is actually stored in memory as the sequence
2, 4, 3, 6, 2, 5, 9, 8, 1
The element at row 3, column 2 of matrix A (value = 5) can also be identified as
element 6 in the actual storage sequence. To access this element, you have a choice
of using the standard A(3,2) syntax, or you can use A(6), which is referred to as
linear indexing.
Subscripting
Nonconsecutive Elements
To refer to nonconsecutive elements in a matrix, use the colon
operator with a step value. The m:3:n in this expression means to
make the assignment to every third element in the matrix. Note that
this example uses linear indexing:
B = magic(4);
B(1:3:16) = -10
B = -10 2 3 -10
5 11 -10 8
9 -10 6 12
-10 14 15 -10
MATLAB supports a type of array indexing that uses one array as the
index into another array. You can base this type of indexing on either
the values or the positions of elements in the indexing array.
Subscripting
Individual elements in a matrix are denoted by a row index and a column index.
To pick out the third element of the vector u type:

>> u = rand(1,5)
u=
0.9218 0.7382 0.1763 0.4057 0.9355
>> u(3)
ans =
0.1763
Subscripting
Individual elements in a matrix are denoted by a row index and a column index.
To pick out the third element of the vector u type:

>> u = rand(1,5)
u=
0.9218 0.7382 0.1763 0.4057 0.9355
>> u(3)
ans =
0.1763

You can use the vector [1 2 3] as an index to u. To pick the first three
elements of u type
>> u([1 2 3])
ans =
0.9218 0.7382 0.1763
Subscripting
Here is an example of value-based indexing where array B
indexes into elements 1, 3, 6, 7, and 10 of array A. In this
case, the numeric values of array B designate the intended
elements of A:
A = 5:5:50
A = 5 10 15 20 25 30 35 40 45 50
B = [1 3 6 7 10];
A(B)
ans = 5 15 30 35 50
Subscripting
Remembering what the colon operator does, you can abbreviate this to
>> u(1:3)
ans =
0.9218 0.7382 0.1763
Subscripting
Remembering what the colon operator does, you can abbreviate this to
>> u(1:3)
ans =
0.9218 0.7382 0.1763

You can also use a variable as a subscript:


>> i = 1:3;
>> u(i)
ans =
0.9218 0.7382 0.1763
Subscripting
Two dimensional matrices are indexed the same way, only you have
to provide two indices:
>> a = [1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
>> a(3,2)
Subscripting
Two dimensional matrices are indexed the same way, only you have
to provide two indices:
>> a = [1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
>> a(3,2)
ans =
8
Subscripting
Two dimensional matrices are indexed the same way, only you have
to provide two indices:
>> a = [1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
>> a(3,2)
ans =
8
>> a(2:3,3)
Subscripting
Two dimensional matrices are indexed the same way, only you have
to provide two indices:
>> a = [1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
>> a(3,2)
ans =
8
>> a(2:3,3)
ans =
6
9
Subscripting

>> a(2,:)
Subscripting

>> a(2,:)
ans =
456
Subscripting

>> a(2,:)
ans =
456
>> a(:,3)
Subscripting
>> a(2,:)
ans =
456
>> a(:,3)
ans =
3
6
9
Subscripting
>> a(2,:)
ans =
456
>> a(:,3)
ans =
3
6
9
The last two examples use the colon symbol as an index, which matlab interprets as the
entire row or column. If a matrix is addressed using a single index, matlab counts the
index down successive columns:
>> a(4)
ans =
2
>> a(8)
ans =
6
End as a subscript
To access the last element of a matrix along a given dimension, use end as a
subscript (matlab version 5 or later). This allows you to go to the final element
without knowing in advance how big the matrix is. For example:
>> q = 4:10
q=
4 5 6 7 8 9 10
>> q(end)
ans =
10
End as a subscript
To access the last element of a matrix along a given dimension, use end as a
subscript (matlab version 5 or later). This allows you to go to the final element
without knowing in advance how big the matrix is. For example:
>> q = 4:10
q=
4 5 6 7 8 9 10
>> q(end)
ans =
10
>> q(end-4:end)
End as a subscript
To access the last element of a matrix along a given dimension, use end as a
subscript (matlab version 5 or later). This allows you to go to the final element
without knowing in advance how big the matrix is. For example:
>> q = 4:10
q=
4 5 6 7 8 9 10
>> q(end)
ans =
10
>> q(end-4:end)
ans =
6 7 8 9 10
End as a subscript
To access the last element of a matrix along a given dimension, use end as a
subscript (matlab version 5 or later). This allows you to go to the final element
without knowing in advance how big the matrix is. For example:
>> q = 4:10
q=
4 5 6 7 8 9 10
>> q(end)
ans =
10
>> q(end-4:end)
ans =
6 7 8 9 10
>> q(end-2:end)
End as a subscript
To access the last element of a matrix along a given dimension, use end as a
subscript (matlab version 5 or later). This allows you to go to the final element
without knowing in advance how big the matrix is. For example:
>> q = 4:10
q=
4 5 6 7 8 9 10
>> q(end)
ans =
10
>> q(end-4:end)
ans =
6 7 8 9 10
>> q(end-2:end)
ans =
8 9 10
This technique works for two-dimensional matrices as well:
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

>> a(end,end)
ans =
13
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

>> a(2,end-1:end)
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

>> a(2,end-1:end)
ans =
2 11
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

>> a(end-2:end,end-1:end)
End as a subscript
>> a=spiral(4)
a=
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

>> a(end-2:end,end-1:end)
ans =
2 11
3 12
14 13
Using Logicals in Array Indexing
A logical array index designates the elements of
an array A based on their position in the indexing
array, B, not their value. In this masking type of
operation, every true element in the indexing
array is treated as a positional index into the
array being accessed.
Using Logicals in Array Indexing
In the following example, B is a matrix of logical ones and zeros. The
position of these elements in B determines which elements of A are
designated by the expression A(B):
A = [1 2 3; 4 5 6; 7 8 9]
A= 1 2 3
4 5 6
7 8 9

B = logical([0 1 0; 1 0 1; 0 0 1]);
B= 0 1 0
1 0 1
0 0 1
A(B)
ans = 4
2
6
9
Using Logicals in Array Indexing
The find function can be useful with logical arrays as it returns
the linear indices of nonzero elements in B, and thus helps to
interpret A(B):

find(B)
ans = 4
2
6
9
Using Logicals in Array Indexing
Logical Indexing – Example 1
This example creates logical array B that satisfies the
condition A > 0.5, and uses the positions of ones in B to
index into A:
>> A = rand(3);
>> B = A > 0.5;
>> A(B)=0

A=

0.4387 0 0.4456
0.3816 0.1869 0
0 0.4898 0
Logical Indexing – Example 2
The next example highlights the location of the prime numbers in a
magic square using logical indexing to set the nonprimes to 0:
A = magic(4)
A = 16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
B = isprime(A)
B= 0 1 1 1
1 1 0 0
0 1 0 0
0 0 0 0
A(~B) = 0; % Logical indexing
A = 0 2 3 13
5 11 0 0
0 7 0 0
0 0 0 0
Deleting Rows or Columns

To get rid of a row or column set it equal to the empty matrix [ ].


a=[1 2 3;3 4 5;5 6 7]
a=
1 2 3
3 4 5
5 6 7

>> a(:,2)=[ ]
Deleting Rows or Columns

To get rid of a row or column set it equal to the empty matrix [ ].


a=[1 2 3;3 4 5;5 6 7]
a=
1 2 3
3 4 5
5 6 7

>> a(:,2)=[ ]
a=
1 3
3 5
5 7
Deleting Rows or Columns

To get rid of a row or column set it equal to the empty matrix [ ].


a=[1 2 3;3 4 5;5 6 7]
a=
1 2 3
3 4 5
5 6 7

a(2,:)=[ ]
Deleting Rows or Columns

To get rid of a row or column set it equal to the empty matrix [ ].


a=[1 2 3;3 4 5;5 6 7]
a=
1 2 3
3 4 5
5 6 7

a(2,:)=[ ]
a=
1 2 3
5 6 7
Sub array
It is possible to use select and subset of MATLAB array as tough they were
separate array

a = [ 1 2 3 4;1 2 3 4;1 2 3 4;1 2 3 4]


a=
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

>> b=a(1:3,1:3)

b=

1 2 3
1 2 3
1 2 3
CONCATENATING MATRICES
Concatenation
>> a = [1 2 3;4 5 6;7 8 9]
MATLAB responds with
a=
123
456
789

>> b = [a 10*a; -a [1 0 0;0 1 0;0 0 1] ]


CONCATENATING MATRICES
Concatenation
>> a = [1 2 3;4 5 6;7 8 9]
MATLAB responds with
a=
123
456
789

>> b = [a 10*a; -a [1 0 0;0 1 0;0 0 1] ]


MATLAB responds with
b=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1
CONCATENATING MATRICES
Concatenation
The repmat function can be used to replicate a matrix:
>> a = [1 2; 3 4]
a=
1 2
3 4

>> repmat(a,2,3)
ans =
1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4
CONCATENATING MATRICES
Matrix Concatenation Functions
CONCATENATING MATRICES
Matrix Concatenation Functions
A = ones(2, 5) * 6; % 2-by-5 matrix of 6's
B = rand(3, 5); % 3-by-5 matrix of random values
C = cat(1, A, B); % Concatenate along the first dimension
CONCATENATING MATRICES
Matrix Concatenation Functions
>> A
A=
6 6 6 6 6
6 6 6 6 6
>> B
B=
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
>> C
C=
6.0000 6.0000 6.0000 6.0000 6.0000
6.0000 6.0000 6.0000 6.0000 6.0000
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
CONCATENATING MATRICES
Matrix Concatenation Functions
A = ones(2, 5) * 6; % 2-by-5 matrix of 6's
B = rand(3, 5); % 3-by-5 matrix of random values
C = vertcat( A, B); % Concatenate vertically
CONCATENATING MATRICES
Matrix Concatenation Functions
>> C
C=
6.0000 6.0000 6.0000 6.0000 6.0000
6.0000 6.0000 6.0000 6.0000 6.0000
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
Multidimensional Arrays
MATLAB allows to create arrays with many dimensions as necessary for any given
problem
For example following statements create a 2X3X2 array
>> A (:,:,1)= [1 0 1; 1 1 0];
>> A(:,:,2) = [9 8 7; 6 5 4];
A(:,:,1) =
1 0 1
1 1 0

A(:,:,2) =
9 8 7
6 5 4
whos A
Name Size Bytes Class
A 2x3x2 96 double array
Grand total is 12 elements using 96 bytes
Getting Information About a Matrix
Dimensions of the Matrix
These functions return information about the shape
and size of a matrix.
Getting Information About a Matrix
LENGTH Length of vector.
LENGTH(X) returns the length of vector X. It is equivalent to
MAX(SIZE(X)) for non-empty arrays and 0 for empty ones.
Syntax
n = length(X)
Example:
x = ones(1,8);
n = length(x)
n=
8
x = rand(2,10,3);
n = length(x)
n=
10
Getting Information About a Matrix
LENGTH Length of vector.
LENGTH(X) returns the length of vector X. It is equivalent to
MAX(SIZE(X)) for non-empty arrays and 0 for empty ones.
Syntax
n = length(X)
Example:
x = ones(1,8);
n = length(x)
n=
8
x = rand(2,10,3);
n = length(x)
n=
10
Getting Information About a Matrix
Ndims Number of array dimensions

Syntax
n = ndims(A)
Description
n = ndims(A) returns the number
of dimensions in the array A. The number of dimensions
in an array is always greater than or equal to 2. Trailing
singleton dimensions are ignored.
Getting Information About a Matrix
Ndims Number of array dimensions

>> a=[1 1 1;1 1 1]


a=
1 1 1
1 1 1
>> s=ndims(a)
s=
2
Getting Information About a Matrix
Ndims Number of array dimensions

>> a=[1 1 1;1 1 1]


a=
1 1 1
1 1 1
>> a(:,:,2)=[1 1 1;2 2 2]
a(:,:,1) =
1 1 1
1 1 1
a(:,:,2) =
1 1 1
2 2 2
>> s=ndims(a)
s=
3
Getting Information About a Matrix
Numel
Number of elements in array or subscripted array
expression

Syntax
n = numel(A)
Getting Information About a Matrix
Numel
Number of elements in array or subscripted array expression

>> a=magic(2)
a=
1 3
4 2
>> numel(a)
ans =
4
Getting Information About a Matrix
>> a=magic(2)
a=
1 3
4 2
>> a(:,:,2)=a'
a(:,:,1) =
1 3
4 2
a(:,:,2) =
1 4
3 2
>> numel(a)
ans =
8
Getting Information About a Matrix
Size
Array dimensions

Syntax
D = SIZE(X), for M-by-N matrix X, returns the two-
element row vector

[M,N] = SIZE(X), for matrix X, returns the number of


rows and columns in X as separate
output variables.
Getting Information About a Matrix
Syntax
D = SIZE(X), for M-by-N matrix X, returns the two-
element row vector

>> a=[1 2 3;2 3 4]


a=
1 2 3
2 3 4
>> size(a)
ans =
2 3
Getting Information About a Matrix
Syntax
[m,n] = SIZE(X), for M-by-N matrix X, returns the two-
element row vector

>> a=[1 2 3;2 3 4]


a=
1 2 3
2 3 4
>> [r,c]=size(a)
r=
2
C=
3
Getting Information About a Matrix
Syntax
[m,n] = SIZE(X), for M-by-N matrix X, returns the two-
element row vector

>> a=[1 2 3;2 3 4]


a=
1 2 3
2 3 4
>> [r,c]=size(a)
r=
2
C=
3
Adding Smaller Blocks to a Matrix
To add one or more elements to a matrix where the sizes
are not compatible, you can often just store the new
elements outside the boundaries of the original matrix.
MATLAB automatically pads the matrix with zeros to
keep it rectangular.
Adding Smaller Blocks to a Matrix
To add one or more elements to a matrix where the sizes are not
compatible, you can often just store the new elements outside the
boundaries of the original matrix. MATLAB automatically pads the
matrix with zeros to keep it rectangular.
Construct a 3-by-5 matrix, and attempt to add a new element to it
using concatenation. The operation fails because you are attempting
to join a one-column matrix with one that has five columns:
A = [ 10 20 30 40 50; ...
60 70 80 90 100; ...
110 120 130 140 150];
A = [A; 160]
??? Error using ==> vertcatAll rows in the bracketed expression must
have the same number of columns.
Adding Smaller Blocks to a Matrix
Try this again, but this time do it in such a way that enables
MATLAB to make adjustments to the size of the matrix.
Store the new element in row 4, a row that does not yet exist
in this matrix. MATLAB expands matrix A by an entire
new row by padding columns 2 through 5 with zeros:

A(4,1) = 160
A = 10 20 30 40 50
60 70 80 90 100
110 120 130 140 150
160 0 0 0 0
Adding Smaller Blocks to a Matrix
A = [ 10 20 30 40 50; ...
60 70 80 90 100; ...
110 120 130 140 150];

You can also expand the matrix by adding a matrix instead


of just a single element:
A(4:6,1:3) = magic(3)+100
Adding Smaller Blocks to a Matrix
A = [ 10 20 30 40 50; ...
60 70 80 90 100; ...
110 120 130 140 150];

You can also expand the matrix by adding a matrix instead of just a single
element:
A(4:6,1:3) = magic(3)+100

A= 10 20 30 40 50
60 70 80 90 100
110 120 130 140 150
108 101 106 0 0
103 105 107 0 0
104 109 102 0 0
Adding Smaller Blocks to a Matrix
A = [ 10 20 30 40 50; ...
60 70 80 90 100; ...
110 120 130 140 150];

You do not have to add new elements sequentially.


Wherever you store the new elements, MATLAB pads with
zeros to make the resulting matrix rectangular in shape:
A(4,8) = 300
Adding Smaller Blocks to a Matrix
A = [ 10 20 30 40 50; ...
60 70 80 90 100; ...
110 120 130 140 150];

You do not have to add new elements sequentially. Wherever you store
the new elements, MATLAB pads with zeros to make the resulting
matrix rectangular in shape:
A(4,8) = 300

A= 10 20 30 40 50 0 0 0
60 70 80 90 100 0 0 0
110 120 130 140 150 0 0 0
0 0 0 0 0 0 0 300
Matrix Arithmetic
The list of operators includes
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a=[1 2 3;1 2 3;1 2 3]


a=
1 2 3
1 2 3
1 2 3

>> b=a+10
b=
11 12 13
11 12 13
11 12 13

>> c=a-10
c=
-9 -8 -7
-9 -8 -7
-9 -8 -7
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> d=a*10
d=
10 20 30
10 20 30
10 20 30

>> d=a.*10
d=
10 20 30
10 20 30
10 20 30
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a=[1 2 3;1 2 3;1 2 3]


a=
1 2 3
1 2 3
1 2 3

>> d=a/10
d=
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000

>> v=10\a
v=
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a=[1 2 3;1 2 3;1 2 3]


a=
1 2 3
1 2 3
1 2 3

>> d=a/10
d=
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000

>> v=10\a
v=
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
0.1000 0.2000 0.3000
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> c=a+b
c=
2 4 6
2 4 6
2 4 6
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> c=a-b
c=
0 0 0
0 0 0
0 0 0
Matrix Arithmetic
Matrices can be added and subtracted
(they must be the same size).

>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> m=a*b
m=
6 12 18
6 12 18
6 12 18
Matrix Arithmetic
.* Element-by-element multiplication
>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> m=a.*b
m=
1 4 9
1 4 9
1 4 9
Matrix Arithmetic
./ Element-by-element division
.\ Element-by-element left division

>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> d=a/b
Warning: Matrix is singular to working precision.
d=
NaN NaN NaN
NaN NaN NaN
NaN NaN NaN
Matrix Arithmetic
./ Element-by-element division
.\ Element-by-element left division
>> a
a=
1 2 3
1 2 3
1 2 3

>> b
b=
1 2 3
1 2 3
1 2 3

>> d=a ./ b
d=
1 1 1
1 1 1
1 1 1
Matrix Arithmetic
.^ Element-by-element power

>> a
a=
1 2 3
1 2 3
1 2 3

>> b=a^2
b=
6 12 18
6 12 18
6 12 18

>> c=a.^2
c=
1 4 9
1 4 9
1 4 9
Matrix Arithmetic
.^ Element-by-element power
>> a
a=
1 2 3
1 2 3
1 2 3

>> c=a^3
c=
36 72 108
36 72 108
36 72 108

>> c=a.^3
c=
1 8 27
1 8 27
1 8 27
Matrix Arithmetic
.' Unconjugated array transpose
To convert rows into columns use the transpose symbol ’:

>> a=[1 2 3;1 2 3;1 2 3]

a=

1 2 3
1 2 3
1 2 3

>> b=a'
b=
1 1 1
2 2 2
3 3 3
Matrix Arithmetic
.' Unconjugated array transpose
To convert rows into columns use the transpose symbol ’:

Be careful when taking the transpose of complex matrices.


The transpose operator takes the complex conjugate transpose.
If z is the matrix:

z=[0 0-i;0+2i 1+i]


z=
0 0 - 1.0000i
0 + 2.0000i 1.0000 + 1.0000i
then z’ is:
>> y=z'
y=
0 0 - 2.0000i
0 + 1.0000i 1.0000 - 1.0000i
Matrix Arithmetic
.' Unconjugated array transpose
To convert rows into columns use the transpose symbol ’:

Be careful when taking the transpose of complex matrices.


The transpose operator takes the complex conjugate transpose.
If z is the matrix:
z=[0 0-i;0+2i 1+i]
z=
0 0 - 1.0000i
0 + 2.0000i 1.0000 + 1.0000i
then z’ is:
>> y=z'
y=
0 0 - 2.0000i
0 + 1.0000i 1.0000 - 1.0000i

To take the transpose without conjugating the complex elements, use


the .’ operator. In this case z.’ is:
>> y=z.'
y=
0 0 + 2.0000i
0 - 1.0000i 1.0000 + 1.0000i
Array Manipulation Functions

Rot90 e.g. B = rot90(A)


rotates matrix A counterclockwise by 90 degrees.
a=[1 2 3;3 4 5;4 5 6]
a=
1 2 3
3 4 5
4 5 6

>> b=rot90(a)
b=
3 5 6
2 4 5
1 3 4
Cont…

Eg . Rot90(a,2) rotate array 2*90 degrees counterclockwise

a=[1 2 3;3 4 5;4 5 6]


a=
1 2 3
3 4 5
4 5 6

>> b=rot90(a,2)
b=
6 5 4
5 4 3
3 2 1
fliplr -Flip matrices left-right
Syntax
B = fliplr(A)
Description
B = fliplr(A) returns A with columns flipped in the left-right direction, that
is, about a vertical axis.
If A is a row vector, then fliplr(A) returns a vector of the same length with
the order of its elements reversed. If A is a column vector, then fliplr(A)
simply returns A
>> a=[1 2;3 4]

a=
1 2
3 4

>> b = fliplr(a)
b=
2 1
4 3
Flipud-Flip matrices up-down
Syntax
B = flipud(A)
Description
B = flipud(A) returns A with rows flipped in the up-down direction, that is, about a
horizontal axis.
If A is a column vector, then flipud(A) returns a vector of the same length with the
order of its elements reversed. If A is a row vector, then flipud(A) simply returns A.
a=[1 2;3 4]
a=
1 2
3 4
>> b = flipud(a)
b=
3 4
1 2
Cont…
Flipdim- Flip array along a specified dimension
B = flipdim(A,dim) returns A with dimension dim flipped.

When the value of dim is 1, the array is flipped row-wise down. When dim is 2, the array is
flipped columnwise left to right. flipdim(A,1) is the same as flipud(A), and flipdim(A,2)
is the same as fliplr(A).

Examples
flipdim(A,1)
A=1 4
2 5
3 6
produces
3 6
2 5
1 4
Reshape -reshape array
B = reshape(A,m,n)
returns the m-by-n matrix B whose elements are taken column-wise from A. An error
results if A does not have m*n elements.
a=1:10
a=
1 2 3 4 5 6 7 8 9 10
>> b=reshape(a,2,5) % reshape to 2 rows and 5 columns fill by columns
b=
1 3 5 7 9
2 4 6 8 10
b=reshape(b,[ ],2) % figures out how many rows are needed
b=
1 6
2 7
3 8
4 9
5 10
Diag,triu,tril

a=[1 2 3;2 3 4;4 5 6]


a=
1 2 3
2 3 4
4 5 6
>> diag(a) %extract diagonal using diag
ans =
1
3
6
triu(a) %extract upper triangular part
ans =
1 2 3
0 3 4
0 0 6
tril(a) %extract lower triangular part
ans =
1 0 0
2 3 0
4 5 6
Diag,triu,tril

A = [12 62 93 -8 22];

B = diag(A)

B=
12 0 0 0 0
0 62 0 0 0
0 0 93 0 0
0 0 0 -8 0
0 0 0 0 22
Diag,triu,tril

A = [12 62 93 -8 22];

B = diag(A, -1)

B= 0 0 0 0 0 0
12 0 0 0 0 0
0 62 0 0 0 0
0 0 93 0 0 0
0 0 0 -8 0 0
0 0 0 0 22 0
Diag,triu,tril

A = [12 62 93 -8 22];

B = diag(A,1)
B=
0 12 0 0 0 0
0 0 62 0 0 0
0 0 0 93 0 0
0 0 0 0 -8 0
0 0 0 0 0 22
0 0 0 0 0 0
Shifting and Sorting Matrices
Shift and Sort Functions
Use these functions to shift or sort the elements of a
matrix.

You can sort matrices, multidimensional arrays, and cell


arrays of strings along any dimension and in ascending or
descending order of the elements. The sort functions also
return an optional array of indices showing the order in
which elements were rearranged during the sorting
operation.
Shifting and Sorting Matrices
Circular Shift
CIRCSHIFT Shift array circularly.
B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the values in the
array A by SHIFTSIZE elements.

>> a=[1;5;2;3]
a=
1
5
2
3

>> b=circshift(a,1)
b=
3
1
5
2
Shifting and Sorting Matrices
Circular Shift
CIRCSHIFT Shift array circularly.
B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the values in the
array A by SHIFTSIZE elements.

>> a=[1;5;2;3]
a=
1
5
2
3

>> b=circshift(a,2)
b=
2
3
1
5
Shifting and Sorting Matrices
Circular Shift
CIRCSHIFT Shift array circularly.
B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the values in the
array A by SHIFTSIZE elements.

>> a=[1;5;2;3]
a=
1
5
2
3

>> b=circshift(a,-2)
b=
2
3
1
5
Shifting and Sorting Matrices
Circular Shift
CIRCSHIFT Shift array circularly.
B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the values
in the array A by SHIFTSIZE elements.
Shifting and Sorting Matrices
Circular Shift
CIRCSHIFT Shift array circularly.
B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the values
in the array A by SHIFTSIZE elements.
Shifting and Sorting Matrices

SORT Sort in ascending or descending order..


Y = SORT(X,DIM,MODE)
has two optional parameters.
DIM selects a dimension along which to sort.
MODE selects the direction of the sort
'ascend' results in ascending order
'descend' results in descending order
The result is in Y which has the same shape and type as X.
Shifting and Sorting Matrices

SORT Sort in ascending order..


>> a=[4;3;2;1]
a=
4
3
2
1
>> sort(a)
ans =
1
2
3
4
Shifting and Sorting Matrices

SORT Sort in descending order..


>> a
a=
1
2
3
4
>> sort(a,1,'descend')
ans =
4
3
2
1
Basic Graphics
Basic Plotting -Create a plot, include multiple data
sets, specify linestyle, colors, and markers, plot
imaginary and complex data, add new plots, work
with figure windows and axes,and save figures.

Editing Plots -Edit plots interactively and using


functions, and use the property editor.

Mesh and Surface Plots - Visualize functions of two


variables.
Basic Plotting
•“Creating a Plot”
•“Multiple Data Sets in One Graph”
•“Specifying Line Styles and Colors”
•“Plotting Lines and Markers”
•“Adding Plots to an Existing Graph”
•“Figure Windows”
•“Multiple Plots in One Figure”
•“Controlling the Axes”
•“Axis Labels and Titles”
•“Saving a Figure”
%Creating a Plot
x = 0:pi/100:2*pi
y = sin(x)
plot(x,y)
%Creating a Plot
x = 0:pi/100:2*pi
y = sin(x)
plot(x,y)

%Now label the axes and add a title. The characters \pi create the symbol
π.

xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
%Creating a Plot
x = 0:pi/100:2*pi
y = sin(x)
plot(x,y)

%Now label the axes and add a title. The characters \pi create the symbol π.

xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

Multiple Data Sets in One Graph


y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
%Creating a Plot
x = 0:pi/100:2*pi
y = sin(x)
plot(x,y)

%Now label the axes and add a title. The characters \pi create the symbol π.

xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

Multiple Data Sets in One Graph


y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)

%The legend command provides an easy way to identify the individual plots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
Specifying Line Styles and Colors
It is possible to specify color, line styles, and markers (such as plus
signs or circles) when you plot your data using the plot command.

plot(x,y,'color_style_marker')

Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond
to cyan, magenta, yellow, red, green, blue, white, and black.

Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for
dash-dot. Omit the linestyle for no line.

The marker types are '+', 'o', '*', and 'x' and the filled marker types
are 's' for square, 'd' for diamond, '^' for up triangle, 'v' for down
triangle,'>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h'
forhexagram, and none for no marker.
Example..

x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Adding Plots to an Existing Graph

The hold command enables you to add plots to an existing


graph. When you type
hold on

MATLAB does not replace the existing graph when you issue
another plotting command; it adds the new data to the current
graph, rescaling the axes if necessary.

for eg.-
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:’);
hold on;
plot(x2,sin(x2),'r+')
Figure Windows

Graphing functions automatically open a new figure window if


there are no figure windows already on the screen. If a figure
window exists, MATLAB uses that window for graphics
output.

for eg.-
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:’);
figure;
plot(x2,sin(x2),'r+')
Multiple Plots in One Figure
The subplot command enables you to display multiple plots in
the same window or print them on the same piece of paper.
Typing
subplot(m,n,p)

partitions the figure window into an m-by-n matrix of small


subplots and selects the pth subplot for the current plot.

for eg.-
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;subplot(2,1,1)
plot(x1,sin(x1),'r:');
subplot(2,1,2)
plot(x2,sin(x2),'r+');
Controlling the Axes
The axis command supports a number of options for setting the scaling,orientation, and
aspect ratio of plots.

Setting Axis Limits


By default, MATLAB finds the maxima and minima of the data to choose the axis limits
to span this range. The axis command enables you to specify yourown limits

axis([xmin xmax ymin ymax])

or for three-dimensional graphs,


axis([xmin xmax ymin ymax zmin zmax])

Use the command


axis auto
to reenable MATLAB automatic limit selection.
Setting Axis Aspect Ratio
axis also enables you to specify a number of predefined modes. For
example,
axis square
makes the x-axes and y-axes the same length.
axis equal
Setting Axis Aspect Ratio
axis also enables you to specify a number of predefined modes. For
example,
axis square
makes the x-axes and y-axes the same length.
axis equal

Setting Axis Visibility


You can use the axis command to make the axis visible or invisible.
axis on
makes the axis visible. This is the default.
axis off
makes the axis invisible.
Setting Axis Aspect Ratio
axis also enables you to specify a number of predefined modes. For example,
axis square
makes the x-axes and y-axes the same length.
axis equal

Setting Axis Visibility


You can use the axis command to make the axis visible or invisible.
axis on
makes the axis visible. This is the default.
axis off
makes the axis invisible.

Setting Grid Lines


The grid command toggles grid lines on and off. The statement
grid on
turns the grid lines on and
grid off
turns them back off again.
For example:----
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;subplot(2,1,1)
plot(x1,sin(x1),'r:');
axis square
grid on
subplot(2,1,2)
plot(x2,sin(x2),'r+');
axis square
grid on

Saving a Figure
To save a figure, select Save from the File menu. To save it
using a graphics format, such as TIFF, for use with other
applications, select Export from the File menu. You can also
save from the command line—use the save as command,
including any options to save the figure in a different format.
Three-Dimensional Plots
The plot3 command is the 3-d equivalent of plot:

t = 0:.1:2*pi;
plot3(cos(3*t),sin(3*t),t)

The three dimensional spiral can be better visualised by changing


the orientation of the axes. You can invoke a mouse-based 3-d axis
mover by typing:

Rotate3d

If you click the mouse button down on the plot and drag, you can
move the axes and view the plot from any angle. Release the mouse
button to redraw the data. Type rotate3d again to turn off this
behaviour.
Mesh and Surface Plots
MATLAB defines a surface by the z-coordinates of points above
a grid in the x-y plane, using straight lines to connect adjacent
points.

The mesh and surf plotting functions display surfaces in three


dimensions.

mesh produces wireframe surfaces that color only the lines


connecting the defining points.

surf displays both the connecting lines and the faces of the
surface in color.
For example-

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black')
figure;
surf(X,Y,Z) % A surface plot is similar to a mesh plot except
that MATLAB colors the rectangular faces of the surface.
Basic Data Analysis
The following functions can be used to perform data analysis functions:

max  maximum
min  minimum
find  find indices of nonzero elements
mean average or mean
median  median
std  standard deviation
sort  sort in ascending order
sortrows  sort rows in ascending order
sum  sum of elements
prod product of elements
diff difference between elements
trapz  trapezoidal integration
cumsum  cumulative sum
cumprod  cumulative product
cumtrapz  cumulative trapezoidal integration
max  maximum
Example:
>> a=magic(3)
a=
8 1 6
3 5 7
4 9 2
>> m=max(a)
m=
8 9 7
>> max(m)
ans =
9
>> [v,ind] = max(m)
v=
9
ind =
2
Or
>> max(max(a))
ans = 9
find  find indices of nonzero elements

The find function is often used with relational and logical operators:
Relational operators == equal to
~= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

Logical operators & AND


| OR
~ NOT
xor EXCLUSIVE OR
any True if any element is non-zero
all True if all elements are non-zero
Find

>> s = spiral(3)
s=
789
612
543
We find the elements of s less than 6:
>> s<6
ans =
000
011
111
>> find(s<6)
ans =
3
5
6
8
9
Find

>> s = 100*spiral(3)
s=
700 800 900
600 100 200
500 400 300
>> ind = find(s>400)
ind =
1
2
3
4
7
>> s(ind)
ans =
700
600
500
800
900
Find

>> s(s>400)
ans =
700
600
500
800
900
Programming with
MATLAB

Flow Control
MATLAB has several flow control constructs:
•“if”
•“switch and case”
•“for”
If
The if statement evaluates a logical expression and executes a
group of statements when the expression is true.

if expression
statements
end

When you are nesting ifs, each if must be paired with a matching end. When
using elseif and/or else within an if statement, the general form of the
statement is

if expression1
statements1
elseif expression2
statements2
else
statements3
In this example, if both of the conditions are not
satisfied, then the student fails the course.

attendance=input('attendance = ');
grade_average=input('grade_average =');
if ((attendance >= 0.90) & (grade_average >= 60))
disp('pass')
else
disp('fail')
end;
Another example---

A=input(‘A=‘);
B=input(‘B=‘);
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end
switch and case
The switch statement executes groups of statements based on the value of a
variable or expression.

For example----
method = 'cubic';
switch (method)
case 'bilinear‘
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
case 'nearest'
disp('Method is nearest')
otherwise
disp('Unknown method.')
end
for
Repeat statements a specific number of times
Syntax
for variable = expression
statements
End
for
add two matrix by using for loop

clc;close all;clear all;


a=ones(2,2)
b=5*ones(2,2)
[row,col]=size(b);

for i=1:row
for j=1:col
c(i,j)=a(i,j)+b(i,j)
end
end
c
for
add two matrix without using for loop

>> a
a=
1 1
1 1
>> b
b=
5 5
5 5
>> c=a+b
c=
6 6
6 6
script

Script M-files
Description
A script file is an external file that contains a
sequence of MATLAB statements. By typing
the filename, you can obtain subsequent
MATLAB input from the file. Script files have
a filename extension of .m and are often called
M-files.
Functions
Functions are M-files that can accept input
arguments and return output arguments. The
name of the M-file and of the function should
be the same.
For eg.1
function mean = stat(x)
n = length(x);
mean = sum(x)/n;
Functions
Functions are M-files that can accept input
arguments and return output arguments. The
name of the M-file and of the function should
be the same.
For eg.2
function [mean,stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));
Eg 2.---

function [mean,stdev] = stati(x)


%STAT Interesting statistics.
n = length(x);
mean = sum(x) / n;
stdev = sqrt(sum((x - mean).^2)/n);

You might also like