You are on page 1of 59

!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.

'55)6

!" $"%&'()*%+'" %' ,!-.!/ 012&3+'" 4567 8292:32 7;<

Chapter 1 Introduction to MATLAB

1.1. MATLAB Windows
Table 1.1 MATLAB Windows
Window Purpose
Command Window Main window, enters variables, runs programs
Figure Window Contains output Irom graphic commands
Editor Window Creates and debugs script and Iunction Iiles
Help Window Provides help inIormation
Launch Pad Window Provides access to tools, demos, and documentation
Command History Window Logs commands entered in the Command Window
Workspace Window Provides inIormation about the variables that are used
Current Directory Window Shows the Iiles in the current directory

1.2. MATLAB Commands
MATLAB: Matrix Laboratory.
The basic element oI MATLAB is the matrix. MATLAB commands are similar to the way we express
engineering steps in mathematics, writing computer solutions in MATLAB is much quicker than
writing computer solutions using a low-level language such as C or Fortran.

! Select the MATLAB program Irom a menu in your operating system (Windows or UNIX).
MATLAB command window will appear and you should see the MATLAB prompt (>>),
which tells you that MATLAB is waiting Ior you to enter a command.
! The command to exit MATLAB is quit or exit.
! II you want to save all the variables in the workspace beIore you quit, use the command save.
This automatically saves all the variables in a Iile called matlab.mat.
! AIter quitting MATLAB iI you re-enter once again and iI you want to use all the variables in
the workspace then use the command load, the deIault Iile name is matlab.mat.
! The commands clear all or clear removes all the variables Irom the memory.
! clc # To clear the command window.
! clg # To clear the graphic window.
! clf # To clear the current Iigure a.k.a clear the graph window.
! Ctrl C is used to generate a local abort within MATLAB (in case oI inIinite loop).
! help # a help menu appears.
! To get help on a particular topic, use help topic
For example, help disp.
! MATLAB is a case-sensitive language, Ior example, TIME and time are two diIIerent
variables.
! The command who lists the variables that you have deIined.
! The command whos lists the variables along with their sizes and whether they have nonzero
imaginary part.
1
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

! Also who and whos will list a variable named ans (in command window). Ans stores the value
oI the expression that was last computed but not assigned a name. For example,
a=[2 3];
b=[3 5];
a+b;
a.*b;
who;

The above program will have an output as the Iollowing (iI you type them in command window):
Your variables are:
a ans b
where ans stores the value oI a.*b.

! M-files ( Test1.m, Test2.m,.etc) are used to execute sequence oI commands that are stored in
the Iile in addition to executing commands entered through the key board. M-file (also known
as the script file) is a Iile oI ASCII characters and is generated using an editor or word
processor. To execute the commands in the M-file say Test1.m, we need to enter the command
Test1 in the command window or run the M-file Irom the menu. You can create a new M-file
or edit an existing M-file Irom the menu. Also Ior the existing Iile, you can use the command
edit to edit that Iile.
! indicates comment line in the program.
! .(ellipsis) indicates that the row is to be continued.
! The command echo (in the command window) causes M-files to be viewed as they execute.
echo on turns on echoing oI commands inside Script-Iiles.
echo off turns oII echoing.
Echoing can be turned on and oII with the command echo.
a=[2,3];
b=[3 5];
c=[1:4;10:13];
a+b;
a.*b;
disp(a)
disp(ans)
disp(c)

The above M-file will give us an output without the command echo as,
2 3
6 15
1 2 3 4
10 11 12 13

and an output with the command echo as,
a|2,3|;
b|3 5|;
c|1:4;10:13|;
ab;
a.*b;
disp(a)
2 3
disp(ans)
6 15
2
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

disp(c)
1 2 3 4
10 11 12 13

! The command what is the directory listings oI all the M-files and mat-files.
! The command type Test1.m or type Test1 lists the contents oI a speciIied Iile name.
! To halt a program temporarily, we can use the command pause. The command pause (30) will
halt the program Ior 30 seconds. To continue with our program we need to hit the enter key on
our keyboard.
% This program reads the values of the matrices a and b
% and computes and displays their addition and subtraction.
a = input('Enter the value of a');
b = input('Enter the value of b');
pause
c = a + b;
d = a - b;
disp('c=')
disp(c)
pause(5)
disp('d=')
disp(d)

! Matlab will accept many oI the same commands as unix. For example, ls will list the current
directory, cd will change it. pwd gives you the present working directory.
! The current directory is also listed in the toolbar above the command window.
! Typing path will give you matlab`s current search path. This is where it looks Ior commands
and scripts to run when you type something into the command window.

1.3. Basic Built In Functions in MALAB
1.3.1. Elementary Math Functions
Table 1.2 Math functions in MATLAB
Function Description
abs() Absolute value
exp() Exponential
Iactorial() The Iactorial Iunction
log() Natural logarithm
log10() Base 10 logarithm
sqrt() Square root
1.3.2. Trigonometric Math Functions
Table 1.3 Trigonometric functions in MATLAB
Function Description Function Description
acos() Inverse cosine cos() Cosine
acot() Inverse cotangent cot() Cotangent
asin() Inverse sine sin() Sine
atan() Inverse tangent tan() Tangent
1.3.3. Hyperbolic Math Functions
Table 1.4 Hyperbolic functions in MATLAB
Function Description Function Description
cosh() Hyperbolic cosine sinh() Hyperbolic sine
coth() Hyperbolic cotangent tanh() Hyperbolic tangent
3
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Note: all the characters in Iunction name should be in the lower case.
4
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Chapter 2 Scalar, Vector and Matrix Operations

2.1. Scalars
2.1.1. Special Values
pi: $ (22/7 or 3.1416)
i, j: 1 %
inf: & (InIinity, Ior example, it will be the result Ior any number divided by zero)
nan: Not a number, Ior example, it will be the result Ior the division oI zero by zero
clock: This element returns the current time in a six-element row vector containing year, month, day,
hour, minute and seconds.
date: This Iunction returns the current date in a character string Iormat, such as 20-Jun-92.

! However, iI you use i as a counting index, or declare it as any other value, it will no longer be a
complex number.

Consider the Iollowing program:
a=2*pi;
fprintf('a=%2.0f \n',a)
b=5;
c=b/0;
fprintf('c=%2.0f \n',c)
fprintf('d=%2.0f \n',0/0)
clock
date

The output will be:
a= 6
Warning: Divide by zero.
> In C:\MATLAB701\work\Untitled1.m at line 4
c=Inf
Warning: Divide by zero.
> In C:\MATLAB701\work\Untitled1.m at line 6
d=NaN
ans =
1.0e+003 *
2.0010 0.0100 0.0010 0.0140 0.0160 0.0506

ans =
01-Oct-2001

2.1.2. Scalar Operations
Table 2.1 Arithmetic operators for scalars
Character Description
Addition
- Subtraction
* Scalar and array multiplication
/ Right division
\ LeIt division
` Exponentiation
Assignment operator
() Parenthesis; sets precedence, encloses input arguments in Iunctions

5
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Precedence in Arithmetic Operations:
Precedence Operation
1 Parenthesis
2 Exponentiation, leIt to right
3 Multiplication and division, leIt to right
4 Addition and subtraction, leIt to right

Arithmetic operation between two scalars:
Operation Algebraic form MATLAB expression
Addition a b a b
Subtraction a b a b
Multiplication a ' b a * b
Right division
b
a
a / b
Exponentiation a ` b
b
a
LeIt division
a
b
a \ b

Example 1:
Consider the Iollowing program:
a=2;
b=3;
x=a+b;
fprintf('a=%1.0f\n',x)
count=1;
count=count+1;
count
time=0.0;
time=5.0;
disp('time')
disp(time)

The above program will give us the Iollowing output:
a=5
count =
2
time
5

Example 2:
Consider the Iollowing program:
%area of a trapezium 1/2 * height * (base1 +base2)
h=2;
b1=3;
b2=5;
area=0.5*h*(b1+b2);
disp('area')
disp(area)

The output will be:
area
8

6
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

! The expression
3 2
2
2 6.3
0.05005 3.14
x x x
x x
% ( %
( %
can be written in MATLAB as,

(x`3-2*x`2x-6.3)/(x`20.05005*x-3.14)

2.2. Matrices and Vectors
A matrix is a set oI numbers arranged in a rectangular grid oI rows and columns.
Scalar # a 3.5; or a |3.5|;
Vector # b |1.5 , 3.1|; or b |1.5 3.1|;

The previous example is a row vector. It can be a column vector as well, such as,
b |1.5 or b |1.5 ; 3.1|;
3.1|;
Matrix # c can also be written as c |-1 0 0; 1 1 0; 1 1 0; 0 0 2|;
1 0 0
1 1 0
1 1 0
0 0 2
%
) *
+ ,
+
% + ,
+ ,
- .
,
or c |-1, 0, 0; 1, 1, 0; 1, 1, 0; 0, 0, 2|; or c |-1 0 0 or c |-1, 0, 0
1 1 0 1, 1, 0
1 1 0 1, -1, 0
0 0 2|; 0, 0, 2|;

The above matrix has 4 rows and 3 columns. Any element oI the matrix is denoted by c(i, j) where i is
the row # and j is the column #.

! The command size(a) gives the size oI a speciIic matrix a.
a|1:4;10:13|;

size(a) will give us the Iollowing output:
ans
2 4

The Number oI Rows is considered the Iirst dimension (hence 2) and the number oI columns is
considered the second dimension (hence 4). The dimension

! The command length(a) returns the length oI a vector or the longest dimension oI a 2-D array
a|1:4;10:13|;
length(a) will give us the Iollowing output:
ans
4

b|1:5|;
length(b) will give us the Iollowing output:
ans
5

7
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6





Table 2.2 Special symbols related to array operations
Character Description
:
Colon; creates vectors with equally spaced elements,
represents range oI elements in arrays
Assignment operator
() Subscriptions oI arrays
|| Brackets; Iorms arrays, encloses output arguments in Iunctions
,
Comma; separates array subscriptions and Iunction arguments,
separates commands in the same line
; Semicolon; suppresses display, ends row in array
Single quote; matrix transpose, creates string

2.3. Special Matrices:
magic: The magic Iunction generates an n ' n matrix constructed Irom the integers Irom 1 through n
2
.
The integers are ordered in such a way that all the row sums and all the column sums are equal to the
same number.
zeros: The zeros Iunction generates a matrix containing all zeros.
ones: The ones Iunction generates a matrix containing all ones.
eye: The eye Iunction generates an identity matrix.

Consider the Iollowing program:
disp(magic(3))
disp('matrix of zeros')
a=zeros(3)
b=zeros(3,2)
c=[1 2 3 ; 4 2 5]
d=zeros(size(c))
disp('matrix of ones')

a=ones(3)
b=ones(3,2)
c=[1 2 3;4 2 5]
d=ones(size(c))
disp('identity matrix')
a=eye(3)
b=eye(3,2)
d=eye(size(c))

The output will be:
8 1 6
3 5 7
4 9 2
matrix of zeros
a =
0 0 0
0 0 0
0 0 0
b =
0 0
0 0
0 0
8
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

c =
1 2 3
4 2 5
d =
0 0 0
0 0 0
matrix of ones
a =
1 1 1
1 1 1
1 1 1
b =
1 1
1 1
1 1
c =
1 2 3
4 2 5
d =
1 1 1
1 1 1
identity matrix
a =
1 0 0
0 1 0
0 0 1
b =
1 0
0 1
0 0
d =
1 0 0
0 1 0

2.4. Initializing Matrices
There are 4 methods:
! Explicit lists
! Data Iile
! Colon operator
! User input

2.4.1. Explicit Lists
c |-1 0 0; 1 1 0; 1 1 0; 0 0 2|;

! The name of the matrix must start with a letter and can contain up to 19 characters that are
digits, letters and the underscore character.
! When we deIine a matrix, MATLAB will print the value oI the matrix on the next line
unless we suppress the printing with the semicolon aIter the deIinition.

II a single row vector is too long then we can use ellipsis (.) which is simply three periods.

Examples:
F |1 52 64 197 42 42 55 82 22 109|; can be written as,
F |1 52 64 197 42 42 .
55 82 22 109|;

9
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

In Iact, ellipsis can be used in any line oI a MATLAB program in order to show the continuation.

Concatenation: II b |1.5 3.1| and s |3.0 b| then s matrix is equivalent to |3.0 1.5 3.1|.
What about g|b` b`| and g|b`;b`|?
Consider the Iollowing 2 MATLAB statements:
s |3.0 1.5 3.1|;
s(2) -1.0;

The new s matrix is |3.0 1.0 3.1|.

More examples:
s |3.0 1.0 3.1|;
s(4) 5.5;
s(8) 9.5;

The resultant s matrix is s |3.0 1.0 3.1 5.5 0 0 0 9.5|.
This example shows that iI additional entries are concatenated beyond the original range oI the matrix,
the new matrix is padded with zeros in between those entries.

2.4.2. Data File:
Matrices can be deIined Irom inIormation that has been stored in a data file. MATLAB can interIace to
2 diIIerent types oI data files.

! MAT files: Data stored in a memory-eIIicient binary Iormat. They are preIerable Ior data that
are going to be generated and used by MATLAB programs only.
! ASCII files: Data stored in ASCII characters. They are necessary iI the data are to be shared
(imported or exported) with programs other than MATLAB.

2.4.2.1. Generating MAT Files:
Consider the Iollowing program.
a = [2 3];
b = [4 5];
c = a + b;
d = a - b;
save data c d;
disp('c=')
disp(c)
disp('d=')
disp(d)

The above program will automatically generate a data.mat Iile. The output oI the above program is:
c
6 8
d
-2 -2

Now consider another program which will use the saved value Irom the data.mat Iile
load data.mat; %Now data is a matrix
c=data(1,:);
d=data(2,:);
10
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

e = c + d;
disp('e=')
disp(e)

The output oI the above program will be:
e
4 6

! save filename x y z -append adds the variables to an existing MAT file.

2.4.2.2. Generating ASCII Files:
Rules:
! The ASCII files must contain only numeric inIormation. We can use in the ASCII file Ior
comments lines.
! Each row oI the ASCII files must contain the same # oI data values to be read by another
program in MATLAB.
! ASCII files are generated in 3 ways:

2.4.2.2.1. By a MATLAB program:
Consider the Iollowing program:
a = [2 3];
b = [4 5];
c = a + b;
d = a - b;
save data.dat c d -ascii;
disp('c=')
disp(c)
disp('d=')
disp(d)

It will create the Iollowing output:
c
6 8
d
-2 -2

It will also create an ASCII file called data.dat as the Iollowing:
6.0000000e+000 8.0000000e+000
-2.0000000e+000 -2.0000000e+000

Consider another program which will use the data stored in the data.dat Iile.
load data.dat;
x = data(1,:);
y = data(2,:);
e = x + y;
disp('e=')
disp(e)

The output oI the above program is:
e
4 6
11
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Note:
! By loading the ascii Iile, the data value will be automatically stored in a matrix data (with the
same name as the data Iile) which will have the same size as the data.
! Though values oI the variables c and d were stored in the data.dat Iile, they can be read as a
variable matrix (data) Ior our case.

2.4.2.2.2. By a Text Editor or Word Processor:
Using a text editor, create a new Iile as Iollows:
6 8
-2 -2

Save the Iile as data1.dat. Now write the Iollowing MATLAB program:
load data1.dat;
disp(data1)
x = data1(1,:);
disp(x)
y = data1(2,:);
disp(y)
e = x + y;
disp('e=')
disp(e)

It will give us an output oI:
6 8
-2 -2
6 8
-2 -2

e
4 6

2.4.2.2.3. ASCII files can also be generated by a Fortran or C program and it can be used by
MATLAB programs.

2.4.2.3. Colon Operator: Array Indexing
The colon operator creates vectors Irom a matrix by selectively removing rows and columns. It stands
Ior 'All Rows or 'All Columns. It also has other uses.

load data1.dat;
disp(data1)
x = data1(1,:);
disp(x)
y = data1(2,:);
disp(y)
e = x + y;
disp('e=')
disp(e)

The colon operator created x and y vectors Irom the data1 matrix.
h 1:8; is equivalent to the Iollowing row vector |1 2 3 4 5 6 7 8|.
12
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

h 1:2:9; is equivalent to |1 3 5 7 9| with the middle value (2) in the expression h 1:2:9; is the step
increment.

! The colon operator can also select a sub matrix Irom another matrix. For example,
c = [-1 0 0; 1 1 0; 1 -1 0; 0 0 2];

disp('c=')
disp(c)
c1 = c(:,2:3);
c2 = c(3:4,1:2);
disp('c1=')
disp(c1)
disp('c2=')
disp(c2)

The above program will have the Iollowing output:
c
-1 0 0
1 1 0
1 -1 0
0 0 2
c1
0 0
1 0
-1 0
0 2
c2
1 -1
0 0

! a ||; where a is an empty matrix. Empty matrix is diIIerent Irom matrix that contains only
zeros.
Consider the Iollowing program:
c = [-1 0 0; 1 1 0; 1 -1 0; 0 0 2];
disp('c=')
disp(c)
x = c(:);
disp('x=')
disp(x)

It will give us the Iollowing output:
c
-1 0 0
1 1 0
1 -1 0
0 0 2

x
-1
1
1
13
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

0
0
1
-1
0
0
0
0
2

Here, c(:) is equivalent to one long column oI matrix that contains Iirst column oI c, Iollowed by
second column and so on. This is because matlab stores arrays by Iirst knowing their size, then
numbering all oI the entries starting with the Iirst column, going to the second column, and so on. The
numbering scheme is column-wise.

2.4.2.4. User Input:
The values Ior a matrix can be entered through the keyboard. Consider the Iollowing program:
% This program reads the values of the matrices a and b
% and computes and displays their addition and subtraction.
a = input('Enter the value of a');
b = input('Enter the value of b');
c = a + b;
d = a - b;
disp('c=')
disp(c)
disp('d=')
disp(d)

As the user runs the program, he needs to input the values oI matrices a and b to compute and display
the values oI c and d. So the output would be:
Enter the value of a [2 3]
Enter the value of b [3 4]
c=
5 7
d=
-1 -1
Another output would be (a and b are both matrices other than vectors)
Enter the value of a [2,3;3,4]
Enter the value of b [3,4;4,5]
c=
5 7
7 9
d=
-1 -1
-1 -1

2.5. Array / Matrix Operation
2.5.1. Arithmetic Operators
All arithmetic operators Ior scalars also work Ior arrays. ReIer to Tables 2.1 and 2.2. Below is some
additional ones which apply to arrays only. The period used beIore any operation tells matlab to
perIorm that operation elementwise.`
Table 2.3 Arithmetic operators for arrays
Character Description
.* Element-by-element multiplication oI arrays
14
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

./ Element-by-element right division
.\ Element-by-element leIt division
.` Element-by-element exponentiation

Precedence (higher to lower):
1. transpose (.`), power (.^), complex conjugate transpose ('), matrix power (^)
2. unary operator: logical negation (~)
3. multiplication (.`), right division (./), leIt division (.\), matrix multiplication (`), matrix right division
(/), matrix leIt division (\)
4. addition (+), subtraction (-)
5. colon operator (:)
! For the operators with the same precedence, the executions proceed Irom leIt to right.

Consider the Iollowing program:
a=[1 3 2; 3 5 4; 2 5 4];
b=[2 3 1;6 8 1; 9 7 5];
c=a.*b
d=a*b

We will have the Iollowing output:
c =
2 9 2
18 40 4
18 35 20
d =
38 41 14
72 77 28
70 74 27

! We have to be very careIul so that the matrix dimensions agree in both the array and the matrix
operations.
! An array operation can be between a scalar and a nonscalar (vector or matrix) but the matrix
operation has to be between nonscalars.

Consider the Iollowing program:
a=[2 4 7];
b=3*a
b=3.*a

c=a/5
c=a./5

It will give us the Iollowing output:
b =
6 12 21
b =
6 12 21
c =
0.4000 0.8000 1.4000
c =
0.4000 0.8000 1.4000

! The point to note in the above program is that when we consider operations between a scalar and a
matrix, the result is same Ior both the array (.` and ./) and matrix (` and /) commands.
! The array operations Ior the vectors and the matrices are almost similar. Consider the Iollowing
program:
15
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

a=[2 5 6]
b=[2 3 5]
c=a.*b
d=a./b
e=a.\b
f=a.^2
g=a.^b
h=3.0.^a
k=[1:5;-1:-1:-5]
l=ones(size(k))
m=k-l
n=k.*m
o=k.^3

The output should look like the Iollowing:
a =
2 5 6
b =
2 3 5
c =
4 15 30
d =
1.0000 1.6667 1.2000
e =
1.0000 0.6000 0.8333
f =
4 25 36
g =
4 125 7776
h =
9 243 729
k =
1 2 3 4 5
-1 -2 -3 -4 -5
l =
1 1 1 1 1
1 1 1 1 1
m =

0 1 2 3 4
-2 -3 -4 -5 -6
n =
0 2 6 12 20

2 6 12 20 30
o =
1 8 27 64 125
-1 -8 -27 -64 -125

2.5.2. Common Functions:
Consider the Iollowing MATLAB statement:
b sin(x);

sin(x): calculates the sine oI the angle x (radians).
! The above statement is valid iI an angle is a scalar or iI an angle is a matrix. If angle is a matrix,
then the function will be applied element bv element to the values in the matrix.
! A Iunction can have no arguments (pi), one argument (sin(angle)) or more arguments (rem(x,y)).
! A Iunction can also be nested as, y log(abs(x)).

Consider the Iollowing program:
x=[2.4 0.0 5.5; -1.2 -0.3 -1.7]
16
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

abs_x=abs(x) %It computes the absolute value of x.
sqrt_x=sqrt(x) %It computes the square root of x.
round_x=round(x) %It rounds x to nearest integer.
fix_x=fix(x) %It rounds x to the nearest integer toward zero.
floor_x=floor(x) %It rounds x to the nearest integer toward minus infinity.
ceil_x=ceil(x) %It rounds x to the nearest integer toward infinity.
sign_x=sign(x) %It returns -1 if x<0, 0 if x=0 and 1 if x>0.
exp_x=exp(x) %It returns the value of e to the power x.
log_x=log(x) %It returns the natural logarithm of x to the base e.
log10_x=log10(x) %It returns the common logarithm of x to the base 10.
a=[4 5];b=[2 2];
rem_ab=rem(a,b) %It returns the remainder of a/b.

Output:
x =
2.4000 0 5.5000
-1.2000 -0.3000 -1.7000
abs_x =
2.4000 0 5.5000
1.2000 0.3000 1.7000
sqrt_x =
1.5492 0 2.3452
0 + 1.0954i 0 + 0.5477i 0 + 1.3038i
round_x =
2 0 6
-1 0 -2
fix_x =
2 0 5
-1 0 -1
floor_x =
2 0 5
-2 -1 -2

ceil_x =
3 0 6
-1 0 -1
sign_x =
1 0 1
-1 -1 -1
exp_x =
11.0232 1.0000 244.6919
0.3012 0.7408 0.1827
Warning: Log of zero.
> In C:\matlab_sv12\work\Untitled1.m at line 10
log_x =
0.8755 -Inf 1.7047
0.1823 + 3.1416i -1.2040 + 3.1416i 0.5306 + 3.1416i
Warning: Log of zero.
> In C:\matlab_sv12\toolbox\matlab\elfun\log10.m at line 13
In C:\matlab_sv12\work\Untitled1.m at line 11
log10_x =
0.3802 -Inf 0.7404
0.0792 + 1.3644i -0.5229 + 1.3644i 0.2304 + 1.3644i
rem_ab =
0 1

2.5.3. Transpose of a Matrix:
The transpose oI a matrix is a new matrix in which the rows oI the original matrix are the columns oI
the new matrix. II a matrix contains a complex value then we can have both the complex conjugate
transpose and complex nonconjugate transpose. The Iollowing program should explain these terms
more clearly.

Program:
17
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

disp('The original Matrices')
a = [ 2i+3 3; 5 4i-5]
aa = [2 3;5 -4]
disp('The nonconjugated transpose :')
disp('There are three ways to compute this.')
b = transpose(a) %complex
c = a.' %complex
d = conj(a') %complex
e = aa.' %noncomplex
disp('The conjugated transpose :')
disp('There are two ways to compute this.')
f = a' %complex
g = ctranspose(a) %complex
h = aa.' %noncomplex

Output:
The original Matrices
a =
3.0000 + 2.0000i 3.0000
5.0000 -5.0000 + 4.0000i
aa =
2 3
5 -4
The nonconjugated transpose :
There are three ways to compute this.
b =
3.0000 + 2.0000i 5.0000
3.0000 -5.0000 + 4.0000i
c =
3.0000 + 2.0000i 5.0000
3.0000 -5.0000 + 4.0000i
d =
3.0000 + 2.0000i 5.0000
3.0000 -5.0000 + 4.0000i
e =
2 5
3 -4
The conjugated transpose :
There are two ways to compute this.
f =
3.0000 - 2.0000i 5.0000

3.0000 -5.0000 - 4.0000i

g =
3.0000 - 2.0000i 5.0000
3.0000 -5.0000 - 4.0000i
h =
2 5
3 -4

2.5.4. Dot Product ---- dot(a,b):
The dot product is the scalar computed Irom two vectors oI the same size.
1
( , )
n
i i
i
dot product dot a b a b
/
/ /
0
In MATLAB, dot product can be also computed as, sum(a.`b), where both a and b are either row or
column vectors. II a is a row vector and b is a column vector, then the computation could be done with
either oI the Iollowing commands:

sum(a`.`b) or
18
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

b
sum(a.`b`).
or iI a and be are both column vectors you may write
a`*b. This is the inner product` and produces a scalar result
on the other hand:
a*b` gives the Outer product` and produces a matrix result.

2.5.5. Cross Product ---- cross(a,b):
The command cross(a,b) returns the cross product oI the vectors a and b. Both a and b must be 3
element vectors.

2.5.6. Matrix Multiplication ---- a`b:
1
*
n
if ik kf
k
c a b
c a
/
/
/
0
The Iirst matrix a must have the same number oI elements in each row as there are in the columns oI
the second matrix b. The resultant matrix will have the same number oI rows oI the Iirst matrix and
same number oI columns as the second matrix. We note that the inner dimension` oI both matrices
must be the same. An example is A|3x5| * B|5x10| C|3x10|.
Note: II f and g are two row vectors, the dot product may also be computed as f`g` (Matrix
multiplication).

2.5.7. Matrix Powers ---- a^n:
The command Ior the power oI a matrix a is a^2 (where, power is equal to 2). a^2 is equivalent to a`a.
Similarly, a^4 is equivalent to a`a`a`a. To raise a matrix to a power, the matrix must be a square
matrix.

2.5.8. Matrix Inverse ---- inv(a):
By deIinition, iI b is an inverse oI a square matrix a, then a`b or b`a are both equal to an identity
matrix with only the diagonal elements being 1 and other elements being 0.

Program:
a = [4 -1 3]
b = [-2 5 2]

dot_ab1 = dot(a,b)
dot_ab2 = a*b'
cross_ab = cross(a,b)
c = [2 5 1;0 3 -1]
d = [1 0 2;-1 4 -2;5 2 1]
mult_cd = c*d
matrix_power1 = d^2
matrix_power2 = d*d
matrix_inverse = inv(d)
matrix_invmatrix = d*matrix_inverse

Output:
a =
4 -1 3
b =
-2 5 2
19
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

dot_ab1 =
-7
dot_ab2 =
-7
cross_ab =

-17 -14 18
c =
2 5 1
0 3 -1
d =
1 0 2
-1 4 -2
5 2 1
mult_cd =
2 22 -5
-8 10 -7
matrix_power1 =
11 4 4
-15 12 -12
8 10 7
matrix_power2 =
11 4 4
-15 12 -12
8 10 7
matrix_inverse =
-0.2222 -0.1111 0.2222
0.2500 0.2500 0.0000
0.6111 0.0556 -0.1111
matrix_invmatrix =
1.0000 0 0.0000
-0.0000 1.0000 0.0000
-0.0000 -0.0000 1.0000

2.5.9. Determinants ---- det(a):
Program:
a = [2 4 5;1 2 3;0 2 4]
det_a = det(a)

Output:
a =
2 4 5
1 2 3
0 2 4
det_a =
-2


2.6. Formatted Printing of Matrices
2.6.1. Long-Short format
In MATLAB the decimal Iractions are printed using a deIault Iormat (short format) that shows 5
signiIicant decimal digits. II we want values to be displayed in a decimal Iormat with 15 signiIicant
digits, we use the command format long. The Iormat can be returned to a decimal Iormat with 5
signiIicant digits using the command format short. For example:
a = [1.23456789 2.34567891];
disp(a);

With format short, the above program will print,
1.2346 2.3457
20
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


and with format long,
1.23456789000000 2.34567891000000

Now consider a similar program as the Iollowing:
a = [1.23456789 2.34567891];
disp(a);
format long;
disp(a);

The output will be:

1.2346 2.3457
1.23456789000000 2.34567891000000

! format short e command will print the values in scientiIic notation with 5 signiIicant digits and
format long e prints the same but with 15 signiIicant digits. For example:
a = [1234.5678934567 234.56789198];
disp(a);

The above program will print (with the format short e command)
1.2346e+003 2.3457e+002

and the same will print with the format long e command.
1.234567893456700e+003 2.345678919800000e+002

! Format + command (print the sign only):
c = [-1 0 1; 1 1 0; 1 -1 0; 0 0 2];disp(c)
format +;
disp(c)

The output of the above program will be:
-1 0 1
1 1 0
1 -1 0
0 0 2

- +
++
+-
+

When a matrix is printed with the format + command, the only character printed is plus and minus
signs. II a value is positive a plus sign will be printed; iI a value is zero, a space will be printed; iI a
value is negative, a minus sign will be printed.

Table 2.4 Display formats
Command Description
Format bank Two decimal digits
Format compact Eliminates empty lines
Format long Fixed-point Iormat with 14 decimal digits
Format long e ScientiIic notation with 15 decimal digits
Format long g Best oI 15-digit Iixed or Iloating point
21
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Format loose Adds empty lines
Format short Fixed-point Iormat with 4 decimal digits
Format short e ScientiIic notation with 4 decimal digits
Format short g Best oI 5-digit Iixed or Iloating point

2.6.2. Prescribed Formatted Printing
! disp command:

disp('Total # of students in the class =')
n = 20;
disp(n)

The program above will give us the Iollowing output:
Total # of students in the class =
20

! Formatted output (fprintf command):
The speciIiers:

e # Exponential notation
f # Fixed point or decimal notation
g # The values will either use e or f, depending on which is shorter

Consider the Iollowing program:
temp = 78.234567989;
fprintf('The temperature is %f degrees',temp);

It will print
The temperature is 78.234568 degrees

Now consider this:
temp = 78.234567989;
fprintf('The temperature is %e degrees',temp);

It will print
The temperature is 7.823457e+001 degrees

Now,
temp = 78.234567989;
fprintf('The temperature is %g degrees',temp);

will give us an output
The temperature is 78.2346 degrees

Note: II the string \n appears in the Iormat, the line speciIied up to that point is printed, and the rest oI
the inIormation will be printed in the next line.

temp = 78.234567989;
fprintf('The temperature is %g degrees.',temp)
fprintf('It is warm.')

The program above will give us an output as the Iollowing:
22
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

The temperature is 78.2346 degrees.It is warm.

Where as,
temp = 78.234567989;
fprintf('The temperature is %g degrees.\n',temp)
fprintf('It is warm.')

will print:
The temperature is 78.2346 degrees.
It is warm.

And,
fprintf('The temperature is %g degrees.\nIt is warm.',temp)

will print:
The temperature is 78.2346 degrees.
It is warm.

Note: The Iormat speciIiers f, e and g can also contain inIormation to speciIy the number oI
decimal places to print and the number oI positions to allot Ior the corresponding value.

temp = 78.234567989;
fprintf('The temperature is %4.1f degrees.\n',temp)
fprintf('It is warm.')

The program above will give us the Iollowing output:
The temperature is 78.2 degrees.
It is warm.

In the above program the output will contain the value oI temp printed with 4 positions, one oI which
will be a decimal position as shown above.

23
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Chapter 3 Branching Statements

3.1. Relational Operators
MATLAB has six relational operators Ior comparing two matrices oI equal size or two scalars.
Table 3.1 Relational operators
Relational Operator Interpretation
Less than
Less than or equal to
~ Greater than
~ Greater than or equal to
Equal to
~ Not equal to

Consider the Iollowing program:
a = input('a =');
b = input('b =');
if a > b
disp('a is greater than b')
end
if a < b
disp('b is greater than a')
end
if a == b
disp('a is equal to b')
end

Output 1:
a =3
b =4
b is greater than a

Output 2:
a =4
b =2

a is greater than b

Output 3:
a =5
b =5
a is equal to b

Output 4:
a =[2 3 5]
b =[3 7 9]
b is greater than a

Output 5:
a = [2 4 5]
b = [1 3 6]

! When we compare two matrices or vectors using a relational operator, the logical expression is
only true iI all the elements satisIy the condition individually. For example, both a and b vectors
have 3 elements. In order to have the logical expression a > b to be true, all the 3 elements oI a
must be greater than the corresponding elements oI b.
24
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

! All the relational operators have the same precedence.

Consider the Iollowing program and its output
a = input('a =');
b = input('b =');
if a > b
disp('a is greater than b')
end
if a < b
disp('b is greater than a')
end
if a == b
disp('a is equal to b')
end

Output :
a = [2 3]
b = [4 5]
b is greater than a

3.2. Logical Operators
We can also combine two logical expressions using the logical operators.
Table 3.2 Logical Operators
Logical Operator Symbol
and &
or ,
not ~

! The hierarchy Irom highest to lowest, is not, and, and or.

Table 3.3 Result of Logical Operators
A B ~A A [ B A & B
Ialse Ialse true Ialse Ialse
Ialse true true true Ialse
true Ialse Ialse true Ialse
true true Ialse true true

3.3. Simple if Statement:
if logical expression
statement group a
end

Consider the Iollowing program :
n = input('n=')
count = 0;
if n < 50
count = count + 1;
disp('count')
disp(count)
end
disp('count')
disp(count)

Output 1:
25
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

n=30
n =
30
count
1
count
1

Output 2:
n=100
n =
100
count
0

3.4. Nested if Statement:
if logical expression 1
statement group a
if logical expression 2
statement group b
end
statement group c
end


Consider the Iollowing program:
n = input('Enter the value n = ');
count = 0;
if n < 50
count = count + 1;
disp('count')
disp(count)
if n < 25
disp('n is less than 25')
end
disp('n is less than 50')
end
disp('count')
disp(count)

Output 1:
Enter the value n = 100
count
0

Output 2:
Enter the value n = 30
count
1
n is less than 50
count
1

Output 3:
Enter the value n = 20
count
1
n is less than 25
n is less than 50
count
26
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

1

3.5. else Clause:
if logical expression
statement group a
else
statement group b
end

II the logical expression is true, then statement group a is executed. II the logical expression is Ialse,
then statement group b is executed.

Example:
a = input('a=');
b = input('b=');
counta=0;countb=0;
if a > b
disp('a is greater than b')

counta = counta + 1;
else
disp('b is greater than or equal to a')
countb = countb + 1;
end
counta
countb
disp('end of program')

Output 1:
a=5
b=3
a is greater than b
counta =
1
countb =
0
end of program

Output 2:
a=4
b=6
b is greater than or equal to a
counta =
0
countb =
1
end of program

3.6. elseif Clause:
if logical expression 1
statement group a
elseif logical expression 2
statement group b
elseif logical expression 3
statement group c
end
27
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


II logical expression 1 is true, then only statement group a is executed. II logical expression 1 is Ialse
and logical expression 2 is true, then only statement group b is executed. II logical expressions 1 and 2
are Ialse and logical expression 3 is true, then only statement group c is executed. II both the logical
expressions 1 and 2 are true, then only statement group a is executed. II none oI the logical expressions
is true, then none oI the statements within the iI structure is executed.

Example:
a = input('a=');
b = input('b=');
if a > b
disp('a is greater than b')
elseif a < b
disp('b is greater than a')
elseif a ==b
disp('a is equal to b')

end
disp('end of program')

The program above will give us the Iollowing outputs:
Output 1:
a=3
b=5
b is greater than a
end of program

Output 2:
a=5
b=2
a is greater than b
end of program

Output 3:
a=5
b=5
a is equal to b
end of program

Consider the program below:
a = input('a=');
b = input('b=');
c = input('c=');
if a > b
disp('a is greater than b')
elseif b > c
disp('b is greater than c')
elseif c > a
disp('c is greater than a')
end
disp('end of program')

Output 1:
a=3
b=6
c=2
b is greater than c
end of program

Output 2:
28
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

a=3
b=2
c=1
a is greater than b
end of program

3.7. elseif - else Clause:
if logical expression 1
statement group a
elseif logical expression 2

statement group b
elseif logical expression 3
statement group c
else
statement group d
end

II logical expression 1 is true, then only statement group a is executed. II logical expression 1 is Ialse
and logical expression 2 is true, then only statement group b is executed. II logical expressions 1 and 2
are Ialse and logical expression 3 is true, then only statement group c is executed. II both the logical
expressions 1 and 2 are true, then only statement group a is executed. II the logical expressions 1, 2 and
3 are Ialse, then statement group d is executed.

Example:
a = 5; b = 5;
if a > b
disp('a is greater than b')
elseif b > a
disp('b is greater than a')
else
disp('a is equal to b')
end
disp('end of program')

Output:
a is equal to b
end of program

29
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Chapter 4 Loops

4.1. for` Loops:
for index expression
statement group a
end

Rules for for Loops`:
! The index Ior the for loop must be a variable.
! II the expression matrix is a scalar, then the loop will be executed one time, with the index
containing the value oI the scalar.
! II the expression matrix is a row vector, then each time through the loop, the index will contain the
next value in the vector.
! II the expression matrix is a matrix, then each time through the loop, the index will contain the next
column in the matrix.
! Upon completion oI the loop, the index contains the last value used.
! II the colon operator is used to deIine the expression matrix using the Iollowing Iormat:

for k initial:increment:limit

then the number oI times the loop will be executed can be computed using the Iollowing equation:
floor((limit-initial)/increment)1

II the value is negative, the loop is not executed.

Example:
for k 5:4:83

The loop would be executed 20 times with the Iinal value oI k being 81.

Example:
for k = 5
k = k*3
end

Output:
k =
15

Example:
for k = [5 4 9]
x = k*3
end
k

Output:
x =
15
x =
12
x =
30
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

27
k =
9

Program:
for k = [5 4 9;1 2 3]
x = k*3
end
k

Output:
x =
15
3
x =
12
6
x =
27
9
k =
9

3

Example:
for k = 2:5
x = k*3
end
k

Output:
x =
6
x =
9
x =
12
x =
15
k =
5

Example:
for k = 2:3:11
k
x = k*3
end

Output:
k
k =
2
x =
6
k =
5
x =
15
k =
8
x =
24
k =
31
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

11
x =
33
k =
11

! The increment can also be negative, Ior example, for k 5:-1:2

Example:
d = [2 4 7 9 13 20];
for k = 1:6
k
if d(k)<10
vel(k)=2*d(k)

pause
else
vel(k)=3*d(k)
pause
end
end
vel

Example:
d = [2 4 7 9 13 20];
for k = 1:length(d)
k
if d(k)<10
vel(k)=2*d(k)
pause
else
vel(k)=3*d(k)
pause
end
end
vel

Both oI the above programs will give us the Iollowing output :
k =
1
vel =
4
k =
2
vel =
4 8
k =
3
vel =
4 8 14
k =
4
vel =
4 8 14 18
k =
5
vel =
4 8 14 18 39
k =
6
vel =
4 8 14 18 39 60
vel =
4 8 14 18 39 60
32
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


4.2. while loop:
while expression
statement group a

end

II the expression is true, the statement group a is executed. AIter the statements are executed, the
condition is retested. II the expression is still true, the group oI statements is executed again. When the
condition is Ialse, the control shiIts to the statements Iollowing the end statement. II the expression is
always true, the loop becomes an inIinite loop and we need to use the Ctrl-C key to abort it.

The Iollowing program adds the values in a vector x to a scalar variable called sum until a negative
value is reached.

sum = 0;
x = [2 5 7 5 9 0 -2 5 4]
k = 1
while k <= length(x) & x(k) >= 0
sum = sum + x(k)
k = k+1
end
disp('The last value of k')
k

The output oI the program above is as Iollows:
x =
2 5 7 5 9 0 -2 5 4
k =
1
sum =
2
k =
2
sum =
7
k =
3
sum =
14
k =
4
sum =
19
k =
5
sum =
28
k =
6
sum =
28
k =
7
The last value of k
k =
7

Example:
33
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


sum = 0;
x = [2 5 7]
k = 1
while x(k) >= 0
sum = sum + x(k)
k = k+1
end
disp('The last value of k')
k

Output:
k =
1
sum =
2
k =
2
sum =
7
k =
3
sum =
14
k =
4
??? Index exceeds matrix dimensions.
Error in ==> C:\matlabR12\work\Untitled.m
On line 4 ==> while x(k) >= 0

Example:
sum = 0;
x = [2 5 7]
k = 1
while k <= length(x) & x(k) >= 0
sum = sum + x(k)
k = k+1
end
disp('The last value of k')
k

Output:
k =
1
sum =
2
k =
2
sum =
7
k =
3
sum =
14
k =
4
The last value of k

k =
4

34
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Chapter 5 Plotting Capabilities

5.1. X - Y Plot
Our objective is to generate x-y plot Irom data stored in 2 vectors.
x time, s y temp, 1F
0 54.2
1 58.5
2 63.8
3 64.2

There are 3 ways to read this data.
! The data can be read explicitly. For example,
x=[0 1 2 3];
y=[54.2 58.5 63.8 64.2];
disp(x);
disp(y);
plot(x,y),...
title('Temperature Measurement'),...
xlabel('time, s'),...
ylabel('temp, F'),...
grid

will give the Iollowing output in the command window:
0 1 2 3
54.2000 58.5000 63.8000 64.2000

and the Iollowing Iigure in the graphic window:



! The data can be read using the user input. For example consider the Iollowing program:

x=input('give the values of time');
y=input('give the values of temperature');
disp(x);
disp(y);
plot(x,y),...
title('Temperature Measurement'),...
xlabel('time, s'),...
ylabel('temp, F'),...
grid

The above program will give us the Iollowing output in the command window:
35
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

give the values of time [0 1 2 3]
give the values of temperature [54.2 58.5 63.8 64.2]
0 1 2 3
54.2000 58.5000 63.8000 64.2000

It will also give us the same plot in the graphic window.
! The data can be read Irom an ASCII file into a matrix and stored in the vectors using colon
operator.

For example, let us consider the Iollowing Iile (data.dat):
0 1 2 3
54.2 58.5 63.8 64.2

and the Iollowing program:
load data.dat;
disp(data);
x=data(1,:);
y=data(2,:);
plot(x,y),...
title('Temperature Measurement'),...
xlabel('time, s'),...
ylabel('temp, F'),...
grid

The output in the command window will be :
0 1.0000 2.0000 3.0000
54.2000 58.5000 63.8000 64.2000

and the plot remains the same.

! We could have also stored the data in a mat file and read the values oI time and temperature
Irom there.

We can also have two graphic windows at the same time. For example,

load data.dat;
disp(data);
x=data(1,:);
y=data(2,:);

plot(x,y),...
title('Temperature Measurement'),...
xlabel('time, s'),...
ylabel('temp, F'),...

grid

plot(y,x),...
title('Temperature Measurement'),...
ylabel('time, s'),...
xlabel('temp, F'),...
grid

will give us only second plot but

load data.dat;
disp(data);
x=data(1,:);
36
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

y=data(2,:);
figure(1)
plot(x,y),...
title('Temperature Measurement'),...
xlabel('time, s'),...
ylabel('temp, F'),...
grid
figure(2)
plot(y,x),...
title('Temperature Measurement'),...
ylabel('time, s'),...
xlabel('temp, F'),...
grid

will give us both the plots.

5.2. 2-D Plot Labels
title(text`) # This command writes the text as a title at the top oI the current plot.
xlabel(text`) # This command writes the text beneath the x-axis on the current plot.
ylabel(text`) # This command writes the text beside the y-axis on the current plot.
text(x,y,`text`) # This command writes the text on the graphics screen at the points speciIied by the
coordinates (x,y) using the axes Irom the current plot. II x and y are vectors then the text is
written in each point.
gtext(text`) # This command writes the text at the position on the graphics screen indicated by the
mouse or arrow keys.
grid # This command adds grid lines to the current plot.

5.3. Plot Commands
plot(x,y) # The command generates a linear plot with x being the independent variable and y being
the dependent variable.
semilogx(x,y) # This command generates a plot with logarithmic scale Ior x and linear scale Ior y.
semilogy(x,y) # This command generates a plot with logarithmic scale Ior y and linear scale Ior x.
loglog(x,y) # This command generates a plot with logarithmic scales Ior both x and y.

Program:
time = [1 2 3 4 5]
temp = [2 5 9 14 20]
figure(1)
plot(time,temp),xlabel('time (min)'),ylabel('temp (c)'),text([1 3],[2 9],...
'critical point'),gtext('current point1'),grid,gtext('current point2')
figure(2)
semilogy(time,temp),xlabel('time (min)'),ylabel('temp (c)'),text([1 3],[2 9],...
'critical point'),gtext('current point1'),grid,gtext('current point2')

Output:
Command Window #
time =
1 2 3 4 5
temp =
2 5 9 14 20

Graphics Window #
Figure No. 1:
37
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Figure No. 2:


! Any Iigure can be saved as .fig extension. For example, figure1.fig.

5.4. Histograms (SKIPPED)
hist(x) # The command plots a histogram with 10 intervals Ior the data stored in vector x.
hist(x,n) # The command plots a histogram with n intervals with data stored in vector x.
hist(x,y) # It plots a histogram Ior the data in vector x with the intervals deIined by the vector y, a
vector with elements in ascending order.
38
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Program:
x = [2 5 7 9 8 3 2 6 9 3 5 4 7 6 5 9 2 4 6 8 5 3 4 6 1 3]
figure(1)
hist(x),title('Scores in midterm')
figure(2)
hist(x,[1 2 4 6])

figure(3)
hist(x,5)

Output in Graphics Window:
Figure No. 1:

Figure No. 2:

Figure No. 3:


5.5. Plotting Options
5.5.1. Multiple Plots
There are three ways to plot multiple curves on the same graph.
! II both x and y are matrices oI the same size, the columns oI x are plotted with the columns oI y in
case oI plot(x,y).
39
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

! We can plot multiple curves on the same graph by using multiple arguments in the plot command,
as in the Iollowing:
plot(x,y,w,z)
# Here, x, y, w and z are vectors. When the command is executed, the curve corresponding to x and
y will be plotted, and then the curve corresponding to w and z will be plotted on the same graph.
! The third way to plot multiple curves on the same graph is with the hold command. The execution
oI another hold command will turn oII the hold on the current graph. The hold on and hold off
commands can also be used to turn on and oII the hold on the current graph.
Table 5.1 Line styles, marker styles and plot color
Line Type Indicator Point Type Indicator Color Indicator
Solid - Point . Red r
Dashed -- Plus + Green g
Dotted : Star ` Blue b
Dashdot -. Circle O White w
X-mark x Invisible i
Square s Black k
Diamond d Yellow y
Triangle (down) v Magenta m
Triangle (up) ^ Cyan c
Triangle (leIt) <
Triangle (right) >
Pentagram p
Hexagram h
No marker <none>

For example to have a plot with dotted blue line with x-mark, we use the Iollowing command:
plot(x,y,`:xb`)

Legend:
The legend command can be written in two ways:
legend(str1,str2,pos) or simply
legend(str1,str2)
Table 5.2 Values of pos in the legend command
Value Meaning
0 Automatic "best" placement (least conIlict with data)
1 Upper right-hand corner (deIault)
2 Upper leIt-hand corner
3 Lower leIt-hand corner
4 Lower right-hand corner
-1 To the right oI the plot
Program:
time = [1 0;2 2;3 4;4 6;5 8]
temp = [2 12;5 15;9 18;14 32;20 57]
x = [1 2 3 4 5]
y = [2 5 11 17 26]
a = [2 4 6]
b = [12 17 19]
c = [0 1 2]
d = [7 11 42]
40
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

figure(1)
plot(time,temp,':+g'),legend('timetemp1','timetemp2'),xlabel('time'),...
ylabel('temp')
figure(2)
plot(x,y,':g',a,b,'-.xb'),legend('xy','ab',2),title('multiple curves')
hold
plot(c,d,'-rO'),legend('xy','ab','cd',2)

Output:
Command Window:
time =
1 0
2 2
3 4
4 6
5 8
temp =
2 12
5 15
9 18
14 32
20 57
x =
1 2 3 4 5
y =
2 5 11 17 26
a =
2 4 6
b =
12 17 19
c =
0 1 2
d =
7 11 42
Current plot held

Graphics Window:
Figure No. 1:

Figure No. 2:
41
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


5.5.2. Sub Plots
The subplot command allows us to split the graphics window into subwindows. The command
subplot(m,n,p) splits the graphics window into m rows, n columns and sets subwindow p as the
current. The subwindows are numbered by row Irom leIt to right, top to bottom.

Program:
time = [1 2 3 4 5 6]
temp = [13 16 20 29 40 48]
x = [1 2 3 4 5]
y = [2 5 11 17 26]
a = [2 4 6]
b = [12 17 19]
c = [0 1 2]
d = [7 11 42]
subplot(2,2,1),plot(time,temp,':+g'),legend('timetemp'),...
xlabel('time'),ylabel('temp')
subplot(2,2,2),plot(x,y,':g',a,b,'-.xb'),legend('xy','ab',2),...
title('multiple curves')

subplot(2,2,3),plot(c,d,'-rO'),legend('cd',1)
Output:
Command Window :
time =
1 2 3 4 5 6
temp =
13 16 20 29 40 48
x =
1 2 3 4 5
y =
2 5 11 17 26
a =
2 4 6
b =
12 17 19
c =
0 1 2

d =
7 11 42
Graphics Window:
42
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6



5.5.3. Special Symbols in Labels
Consider the Iollowing program:
clear all;
clc;
close all;
temp-15.1;
Ior i1:300
temptemp0.1;
x(i)temp;
iI abs(x(i))~3.0
y(i)sign(x(i));
else
y(i)x(i)/3.0;
end
iI x(i)-1
z(i)-1.0-1/x(i);
elseiI x(i)~1
z(i)1-1/x(i);
else
z(i)0.0;
end
w(i)coth(x(i))-1/x(i);
end
plot(x,y, 'r');
hold on
plot(x,z,'b','LineWidth',3);
hold on
plot(x,w,'.-g')
hlegend('Asymptotic','Critical','Optimal',2);
xlabel('\alpha');
ylabel('\xi');
The output will be (in graphic window):
43
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

-15 -10 -5 0 5 10 15
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
2
3
Asymptotic
Critical
Optimal

More character sequences Ior labels are listed in table 5.3.
Table 5.3 Character sequence for labels in plots
Character sequence Symbol Character sequence Symbol Character sequence symbol
\alpha ! \upsilon " \sim ~
\beta # \phi 4 \leg 5
\gamma $ \chi % \inIty &
\delta & \psi ' \clubsuit (
\epsilon ) \omega * \diamondsuit +
\zeta , \Gamma - \heartsuit .
\eta / \Delta 0 \spadesuit 1
\theta 2 \Theta 3 \leItrightarrow 4
\vartheta 6 \Lambda 5 \leItarrow 6
\iota 7 \Xi 8 \uparrow 9
\kappa : \Pi ; \rightarrow <
\lambda = \Sigma > \downarrow ?
\mu \Upsilon @ \circ 1
\nu A \Phi B \pm 7
\xi C \Psi D \geq 8
\pi E \Omega F \propto 9
\rho G \Iorall : \partial ;
\sigma H \exists < \bullet $
\varsigma I \ni = \div >
\tau J \cong ? \neq @
\equiv A \approx B \aleph C
\Im D \Re E \wp
F
\otimes G \oplus H \oslash I
\cap J \cup K \supseteq
L
\supset M \subseteq
N
\subset O
\int
P
\in Q \o R
\rIloor K \lceil L \nabla S
44
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

\lIloor M \cdot \ldots !
\perp T \neg U \prime
\wedge V \times ' \0
\rceil N \surd O \mid ,
\vee W \varpi X \copyright
\langle Y \rangle Z

5.6. 3-D plots
The plot command Ior the 2-D world can be extended into 3-D with plot3. The Iormat is the same as
the 2-D plot, except the data are in triples rather than in pairs.

Program:
x = [0 1 2 3 4 5 6 7 8 9];
y = [1 3 6 9 13 17 20 25 32 40];

height = [ 2 8 9 3 14 6 8 4 19 17];
plot3(x,y,height,'-xb'), title('Elevation above mean sea level'),...
xlabel('x axis'),ylabel('yaxis'),zlabel('zaxis'),...
legend('Height in meter'),grid

Output:
Command Window:
x =
0 1 2 3 4 5 6 7 8 9
y =
1 3 6 9 13 17 20 25 32 40
height =
2 8 9 3 14 6 8 4 19 17
end of program

Graphics Window:


5.7. Mesh Plots and Surface Plots (SKIPPED)
A mesh surIace is generated by a set oI values in a matrix. Each point in the matrix represents the value
oI a surIace that corresponds to the point in the grid. A surIace plot looks like the mesh plot except that
the spaces between the lines are Iilled in.

Program:
[xgrid,ygrid] = meshgrid(1:1:10,1:1:10);
xgrid
ygrid
z = sqrt(abs(1-xgrid.^2-ygrid.^2))
mesh(z), title('mesh plot')
45
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Output:
Command Window :
xgrid =
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
ygrid =
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10
z =
Columns 1 through 7
1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000
2.0000 2.6458 3.4641 4.3589 5.2915 6.2450 7.2111
3.0000 3.4641 4.1231 4.8990 5.7446 6.6332 7.5498
4.0000 4.3589 4.8990 5.5678 6.3246 7.1414 8.0000
5.0000 5.2915 5.7446 6.3246 7.0000 7.7460 8.5440
6.0000 6.2450 6.6332 7.1414 7.7460 8.4261 9.1652
7.0000 7.2111 7.5498 8.0000 8.5440 9.1652 9.8489
8.0000 8.1854 8.4853 8.8882 9.3808 9.9499 10.5830
9.0000 9.1652 9.4340 9.7980 10.2470 10.7703 11.3578
10.0000 10.1489 10.3923 10.7238 11.1355 11.6190 12.1655
Columns 8 through 10
8.0000 9.0000 10.0000
8.1854 9.1652 10.1489
8.4853 9.4340 10.3923
8.8882 9.7980 10.7238
9.3808 10.2470 11.1355
9.9499 10.7703 11.6190
10.5830 11.3578 12.1655
11.2694 12.0000 12.7671
12.0000 12.6886 13.4164
12.7671 13.4164 14.1067

Graphics window:
46
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6



Program:
z = [1 4 6;5 7 13;12 15 23]
mesh(z)

Output:
Command Window :
z =
1 4 6
5 7 13
12 15 23

Graphics Window:

Program:
[xgrid,ygrid] = meshgrid(1:1:10,1:1:10);
z = sqrt(abs(1-xgrid.^2-ygrid.^2));
surf(z), title('surface plot')

Output:
Graphics Window:
47
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6



5.8. Contour Plots (SKIPPED)
Contour plots show lines oI constant elevation or height.
! The command contour(z) draws a contour plot oI matrix z. The number oI contour lines and
their values are chosen automatically by MATLAB.
! The command contour(z,n) produces a contour plot oI matrix z with n contour levels.
! The command contour(z,v) produces a contour plot oI z with contour levels at the values
speciIied by vector v.
! The command pcolor(z) Iunction maps the height to a set oI colors and presents the same
inIormation as the contour(z) plot.
! The command contour3(z) will give us 3-D contour plots.

Program:
[xgrid,ygrid] = meshgrid(-0.5:0.1:0.5,-0.5:0.1:0.5);
z = sqrt(abs(1-xgrid.^2-ygrid.^2));
figure(1)
contour(z),title('Contour plot with default number of control levels')
figure(2)
contour(z,10),title('Contour plot with 10 control levels')
figure(3)
contour(z,[0.8 0.85 0.9]),title('Contour plot with 3 specified interval')
figure(4)
pcolor(z),title('Contour plot with color mapping')
Output:
Figure No. 1:

Figure No. 2:
48
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Figure No. 3:

Figure No. 4:


5.9. Polynomial Regression
5.9.1 Polyfit Function
The MATLAB Iunction Ior computing the best Iit to a set oI data with polynomial with a speciIied
degree is the polyfit Iunction. This Iunction has three arguments:
The x and y coordinates oI the data points and degree N oI the polynomial. Here, x is the independent
variable and y is the dependent variable. The Iunction returns the coeIIicients, in descending powers oI
x. Note that there are N+1 coeIIicients Ior an N-th degree polynomial.
# The polyval Iunction is used to evaluate the polynomial at a set oI data points.
# The Iunction roots determine the roots oI a polynomial.

49
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Program:
x = [1 2 3 4 5 6 7 8 9]
y = [2 4 7 11 16 23 32 45 60]
coef = polyfit(x,y,2)
ybest = polyval(coef,x)
z = [1 -2 -3 10]
root = roots(z)

Output:
x =
1 2 3 4 5 6 7 8 9
y =
2 4 7 11 16 23 32 45 60
coef =
0.9405 -2.4548 4.7143
ybest =
Columns 1 through 7
3.2000 3.5667 5.8143 9.9429 15.9524 23.8429 33.6143
Columns 8 through 9
45.2667 58.8000
z =
1 -2 -3 10
root =
-2.0000
2.0000 + 1.0000i
2.0000 - 1.0000i


50
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Chapter 6 M-File Functions

!"#$%&'# output arguments ) name of the function (input arguments)

The line above deIines the input and output arguments and distinguishes the Iunction Iile Irom the
script Iile.
! The Iirst Iew lines should be comments because they will be displayed iI help is requested Ior
the Iunction name, Ior example, help circle (where circle is the Iunction name).
! The only inIormation returned Irom the Iunction is contained in the output arguments. Always
check to be sure that the Iunction includes a statement that assigns a value to the output
argument.
! The same input and output arguments or matrices can be used in both a Iunction and the
program that reIerences it, although we can use separate input arguments. Any values computed
in the Iunction, other than the output arguments, are not accessible Irom the program.
! A Iunction that is going to return more than one value should show all values to be returned as a
vector in the Iunction statement, as in this example, which will return three values:
function dist, vel, accel] motion(x)
! A Iunction that has multiple input arguments must list the arguments in the Iunction statement,
as shown in the example, which has two input arguments:
function error mse(w,d)
! The special variables nargin and nargout can be used to determine the number oI input and
output arguments respectively.

Case 1: (single input and single output)
Program:
r = [0 1 2]
volume = vol(r);

fprintf('The volumes of the spheres are = ')
disp(volume)
Function (vol.m):
function volume = vol(r)
%This function calculates the volume of spheres
volume = 4/3*pi*r.^3

Output:
r =
0 1 2
volume =
0 4.1888 33.5103
The volumes of the spheres are = 0 4.1888 33.5103

Case 2: (multiple inputs and single output)
Program:
r = [0 1 2];
h = [1 3 5];
volume = vol(r,h);
fprintf('The volumes of the spheres are = ')
disp(volume)

Function (vol.m):
function volume = vol(r,h)
%This function calculates the volume of cylinders
51
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

volume = pi*r.^2.*h

Output:
volume =
0 9.4248 62.8319
The volumes of the spheres are = 0 9.4248 62.8319

Case 3: (single input and multiple outputs)
Program:
r = [0 1 2];
[sarea,volume] = survol(r);
fprintf('The volumes of the spheres are = ')
disp(volume)
fprintf('The surface areas of the spheres are = ')
disp(sarea)

Function (survol.m):
function [sarea,volume] = survol(r)
%This function calculates the volume and surface area of spheres
volume = 4/3*pi*r.^3
sarea = 4*pi*r.^2

Output:
volume =
0 4.1888 33.5103
sarea =
0 12.5664 50.2655
The volumes of the spheres are = 0 4.1888 33.5103
The surface areas of the spheres are = 0 12.5664 50.2655

Case 4: (multiple inputs and multiple outputs)
Program:
r = [3 1 2];
h = [2 4 6];
[volcylinder,volsphere] = vol(r,h);
fprintf('The volumes of the spheres are = ')
disp(volsphere)
fprintf('The volumes of the cylinders are = ')
disp(volcylinder)

Function (vol.m):
function [volcylinder,volsphere] = vol(r,h)
%This function calculates the volume and surface area of spheres
volsphere = 4/3*pi*r.^3
volcylinder = pi*r.^2.*h

Output:
volsphere =
113.0973 4.1888 33.5103
volcylinder =
56.5487 12.5664 75.3982
The volumes of the spheres are = 113.0973 4.1888 33.5103
The volumes of the cylinders are = 56.5487 12.5664 75.3982
Chapter 7 Input/Output Functions

7.1. Opening the Files
fid fopen(filename,permission)

where permissions are:
52
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

'r' Open Iile Ior reading (deIault).
'w' Open Iile, or create new Iile, Ior writing; discard existing contents, iI any.
'a' Open Iile, or create new Iile, Ior writing; append data to the end oI the Iile.
'r' Open Iile Ior reading and writing.
'w' Open Iile, or create a new Iile, Ior reading and writing; discard existing contents, iI any.
'a' Open Iile, or create new Iile, Ior reading and writing; append data to the end oI the Iile.

Example:
fid = fopen('exp.txt','w');

7.2. Closing the Files
fclose(fid) or
fclose('all')

7.3. Writing the Output Files
To write Iormatted data to a Iile, we can use the Iollowing command:
fprintf(fid,format,A,...)

where fid is the Iile identiIication used in the open command, format is the descriptor Iield and A
denotes the output arguments.

7.3.1. Useful Switches
e Exponential notation (using a lowercase e as in 3.1415e00)
E Exponential notation (using an uppercase E as in 3.1415E00)
I Fixed-point notation
g The more compact oI e or I, as deIined in |2|. InsigniIicant zeros do not print.
s String oI characters

\n New line
\t Horizontal tab
\\ Backslash
\'' or '' (two single quotes)
Percent character

Example:
x = 0:.1:1;
y = [x; exp(x)];
fid = fopen('exp.txt','w');
fprintf(fid,'%6.2f %12.8f\n',y);
fclose(fid)

Output: (creates a text Iile called exp.txt containing a short table oI the exponential Iunction)
0.00 1.00000000

0.10 1.10517092
...
1.00 2.71828183

Example:
fprintf('A unit circle has circumference %g.\n',2*pi)
53
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Output:
A unit circle has circumference 6.283186.

Example:
B = [8.8 7.7; 8800 7700]
L = fopen('exp.txt','w');
fprintf(L,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B)
fclose(L)
Output:
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm

7.4. Reading the Input Files
A fscanf(fid,format,si:e)

Where size is an argument that determines how much data is read. Valid options are:
n Read n elements into a column vector.
InI Read to the end oI the Iile, resulting in a column vector containing the same number oI elements
as are in the Iile.
|m,n| Read enough elements to Iill an m-by-n matrix, Iilling the matrix in column order. n can be InI,
but not m.

Example:
An ASCII text Iile called exp.txt looks like:
0.00 1.00000000
0.10 1.10517092
...
1.00 2.71828183

Matlab reads this ASCII Iile back into a two-column MATLAB matrix:
fid = fopen('exp.txt');
a = fscanf(fid,'%g %g',[2 inf]) % It has two rows now.
a = a';
fclose(fid)

54
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

Appendix: Statistical Measurements:

A.1. Simple Analysis
! max(x) # II x is a vector then the Iunction returns the largest value in x. II x is a matrix then the
Iunction returns a row vector containing the maximum element Irom each column.
! max(x,y) # This Iunction returns a matrix the same size as x and y. Each element in the matrix
contains the maximum value Irom the corresponding positions in x and y. Here, either x or y or
both may be scalar.
! a, b] max(x) # In this Iorm, iI x is a vector, then the Iunction stores the maximum value oI x in
a scalar a, and the index oI the maximum values in the scalar b. II there are several identical
maximum values, the index oI the Iirst one Iound is returned. II x is a matrix, then the Iunction
stores the maximum values oI x in a vector a and the indices oI the maximum values in a vector b.
! max(x,],1) # The Iunction returns a row vector containing the maximum element Irom each
column.
! max(x,],2) # The Iunction returns a column vector containing the maximum element Irom each
row.
! min(x) # II x is a vector then the Iunction returns the smallest value in x. II x is a matrix then the
Iunction returns a row vector containing the minimum element Irom each column.
! min(x,y) # This Iunction returns a matrix the same size as x and y. Each element in the matrix
contains the minimum value Irom the corresponding positions in x and y. Here, either x or y or both
may be scalar.
! a, b] min(x) # In this Iorm, iI x is a vector, then the Iunction stores the minimum value oI x in a
scalar a, and the indices oI the minimum values in the scalar b. II there are several identical
minimum values, the index oI the Iirst one Iound is returned. II x is a matrix, then the Iunction
stores the minimum values oI x in a vector a and the indices oI the minimum values in a vector b.
! min(x,],1) # The Iunction returns a row vector containing the minimum element Irom each
column.
! min(x,],2) # The Iunction returns a column vector containing the minimum element Irom each
row.
! mean(x) # II x is a vector, this Iunction computes the average value oI the elements oI the vector
x. II x is a matrix, this Iunction computes a row vector that contains the average value oI each
column.
! mean(x,1) # The Iunction returns a row vector containing the average value Irom each column.
! mean(x,2) # The Iunction returns a column vector containing the average value Irom each row.
! median(x) # II x is a vector, this Iunction computes the median value oI the elements oI the vector
x. II x is a matrix, this Iunction computes a row vector that contains the median value oI each
column. The values oI x can be in any order.
! median(x,1) # The Iunction returns a row vector containing the median value Irom each column.
! median(x,2) # The Iunction returns a column vector containing the median value Irom each row.
! sum(x) # II x is a vector, this Iunction returns the sum oI the elements oI x. II x is a matrix, this
Iunction returns a row vector that contains the sum oI each column.
! sum(x,1) # The Iunction returns a row vector containing the sum oI elements Irom each column.
! sum(x,2) # The Iunction returns a column vector containing the sum oI elements Irom each row.
! prod(x) # II x is a vector, this Iunction returns the product oI the elements oI x. II x is a matrix,
this Iunction returns a row vector that contains the product oI each column.
55
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

! prod(x,1) # The Iunction returns a row vector containing the product oI elements Irom each
column.
! prod(x,2) # The Iunction returns a column vector containing the product oI elements Irom each
row.
! cumsum(x) # II x is a matrix, this Iunction returns a matrix oI the same size that contains the
cumulative sum oI values in each column till that point in column.
! cumsum(x,1) # Same as cumsum(x).
! cumsum(x,2) # II x is a matrix, this Iunction returns a matrix oI the same size that contains the
cumulative sum oI values in each row till that point in row.
! cumprod(x) # II x is a matrix, this Iunction returns a matrix oI the same size that contains the
cumulative product oI values in each column till that point in column.
! cumprod(x,1) # Same as cumprod(x).
! cumprod(x,2) # II x is a matrix, this Iunction returns a matrix oI the same size that contains the
cumulative product oI values in each row till that point in row.

Program:
x = [7 4 5 2]
y = [7 4 5 2; 3 5 9 6]
z = [1 2 3 4; 5 6 7 8]
max_vector = max(x)
max_matrix = max(y)
max_yz = max(y,z)
[a,b] = min(x)
[c,d] = min(y)
max1 = max(y,[],1)
min2 = max(z,[],2)
mean_vector = mean(x)
mean_matrix = mean(y)
mean1 = mean(y,1)
mean2 = mean(z,2)
med_vector = median(x)
med_matrix = median(y)
med1 = median(z,1)
med2 = median(y,2)
sum_vector = sum(x)
prod_matrix = prod(y)
cumprod_vector = cumprod(x)
cumsum_matrix = cumsum(y)
sumsum = sum(sum(x))

Output :
x =

7 4 5 2
y =
7 4 5 2

3 5 9 6
z =
1 2 3 4
5 6 7 8
max_vector =
7
max_matrix =
7 5 9 6
max_yz =
7 4 5 4
5 6 9 8
a =
56
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

2
b =
4
c =
3 4 5 2
d =
2 1 1 1
max1 =
7 5 9 6
min2 =
4
8
mean_vector =
4.5000
mean_matrix =
5.0000 4.5000 7.0000 4.0000
mean1 =
5.0000 4.5000 7.0000 4.0000
mean2 =
2.5000
6.5000
med_vector =
4.5000
med_matrix =
5.0000 4.5000 7.0000 4.0000
med1 =
3 4 5 6
med2 =
4.5000
5.5000
sum_vector =
18
prod_matrix =
21 20 45 12
cumprod_vector =
7 28 140 280
cumsum_matrix =
7 4 5 2
10 9 14 8
sumsum =
18


! sort(x) # II x is a vector then this Iunction sorts the values into ascending order. II x is a matrix
then this Iunction sorts each column into ascending order.
! sort(x,1) # This Iunction returns a matrix oI size x with sorting each column into ascending order.
! sort(x,2) # This Iunction returns a matrix oI size z with sorting each row into ascending order.
! a, b] sort(x) # The sorted values are returned to the matrix a and reordered indices are stored in
the matrix b. We can also use the Iollowing expression,
a, b] sort(x, 2), in which each row is sorted into ascending order and stored in a with the
reordered indices being stored in b.

Program:
x = [7 4 5 2]
y = [7 4 5 2; 3 5 9 6]
z = [1 2 3 4; 8 6 7 5]
sortx = sort(x)
sorty = sort(y)
sort1 = sort(y,1)
sort2 = sort(z,2)
[a,b] = sort(y)
[c,d] = sort(z,2)
57
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6


Output:
x =
7 4 5 2
y =
7 4 5 2
3 5 9 6
z =
1 2 3 4
8 6 7 5
sortx =
2 4 5 7
sorty =
3 4 5 2
7 5 9 6
sort1 =
3 4 5 2
7 5 9 6
sort2 =
1 2 3 4
5 6 7 8
a =
3 4 5 2
7 5 9 6
b =
2 1 1 1
1 2 2 2
c =
1 2 3 4
5 6 7 8
d =
1 2 3 4
4 2 3 1


A.2. Variance and Standard Deviation
[ \
2
1
n
k
k
x
n
]
^
/
%
/
0

Here, ^ is the standard deviation, ] is the average, x
k
is each element and n is the total number oI
elements.


! std(x) # II x is a vector, this Iunction computes the standard deviation oI the values oI x. II x is a
matrix, this Iunction computes a row vector containing the standard deviation oI each column.
! std(x,1) # This Iunction computes the same thing as std(x) with n in the denominator in the above
equation in place oI n-1 within the square root.
! std(x, 0, 1) # This Iunction computes a row vector containing the standard deviation oI each
column with n-1 in the denominator.
! std(x, 0, 2) # This Iunction computes a column vector containing the standard deviation oI each
row with n-1 in the denominator.
! std(x, 1, 1) # This Iunction computes a row vector containing the standard deviation oI each
column with n in the denominator.
! std(x, 1, 2) # This Iunction computes a column vector containing the standard deviation oI each
row with n in the denominator.
Note: The variance is the square oI the standard deviation.
58
!""#$ &'()*+,-(.*' (* !*/0,(.'1 2*) !.3.4 "'1.'55)6

59
! var(x) and var(x,1) compute the same thing as standard deviation but all the values are squared.
! var(x,w) computes the variance using the weight vector, w. The number oI elements in w must
equal the number oI rows in x.

Program:
x = [7 4 5 2]
y = [7 4 5 2; 3 5 9 6]
w = [1 2]
std_vector = std(x)
std_matrix = std(y)
std_n = std(y,1)
std_n2 = std(y,1,2)
varrw = var(y,w)

Output:
x =
7 4 5 2
y =
7 4 5 2
3 5 9 6
w =
1 2
std_vector =
2.0817
std_matrix =
2.8284 0.7071 2.8284 2.8284
std_n =
2.0000 0.5000 2.0000 2.0000

std_n2 =
1.8028
2.1651
varrw =
3.5556 0.2222 3.5556 3.5556

You might also like