Professional Documents
Culture Documents
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
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.
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 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 .
>> 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
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:
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
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
Another_vector*SomethingElse;
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
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 :
Concatenation
Concatenation is the process of joining small matrices to make bigger ones.
1 2 2 3
1 2 2 3
Useful Matrix Generators
MATLAB provides four easy ways to generate
certain simple matrices. These are :
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 :
>> 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
>> 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
>> a(:,2)=[ ]
Deleting Rows or Columns
>> a(:,2)=[ ]
a=
1 3
3 5
5 7
Deleting Rows or Columns
a(2,:)=[ ]
Deleting Rows or Columns
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
>> 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
>> 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
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
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
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
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).
>> 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).
>> 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).
>> 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
>> 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 ’:
>> b=rot90(a)
b=
3 5 6
2 4 5
1 3 4
Cont…
>> 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 = [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.
>> 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
%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)
%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)
%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
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
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)
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.
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)
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.
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
>> 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
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.---