Sunteți pe pagina 1din 55

MATLAB Elementary course

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 1


MATLAB Elementary course

Dedicated to my Dad

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 2


MATLAB Elementary course

GETTING STARTED

INTRUDUCTION:

What is MATLAB?

MATLAB=matrix laboratory.

MATLAB was originally written to provide easy access to matrix software developed
by the ‘LINKPACK ‘and ‘EISPACK’ projects that together presented the state –of-the-art
software for matrix manipulation.

MORE ABOUT MATLAB:

High performance language for technical computing.


Integrates computation, visualization and programing in an easy –to-use user
environment.

USES OF MATLAB:

Math and computation


Algorithm development
Application development, include Graphical User Interface (GUI) building.
Data analysis, exploration and visualization.
Scientific and engineering graphics.

COMPONETS OF MATLAB:

Toolboxes
Basic Window
Extensive Help
GUI
Simulink

ToolBoxes:
Control system
Financial
Image Processing
PDE
Statistics
Communications
Fuzzy Logic
Symbolic Math
Neural Network
Signal Processing
Optimization

And many more …….given following Fig (1)


MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 3
MATLAB Elementary course

Fig (1)

Basic Window:
Command Window
Command History
Workspace Window
Visualization Window
Help Window
Current Folder Window

Fig(2)
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 4
MATLAB Elementary course

Command Window:
MATLAB expressions and statements are evaluated as we type them in
the Command Window, and result of computations is displayed there too.
They are usually of the form.
Variable = expression

(Or) simply

expression

Expressions are usually composed from operators, functions, and variable names. a
variable ans (for answer) is automatically created to which the result is assigned.
A statement is normally terminated at the end of the line. However, a statement can
be continued to the next line with three periods (...) at the end of the line. Several
statements can be placed on a single line separated by commas or semicolons. If the
last character of a statement is a semicolon, display of the result is suppressed, but
the assignment is carried out. This is essential in suppressing unwanted display of
intermediate results.

Fig(3)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 5


MATLAB Elementary course

Edit command Line:

 The line with the >> prompt is called the command line.
The command line in MATLAB can be easily edited in the Command
window. The cursor can be positioned with the left and right arrows and the
Backspace (or Delete) key used to delete the character to the left of the cursor.
A convenient feature is use of the up and down arrows to scroll through the
stack of previous commands. We can, therefore, recall a previous command
line, edit it, and execute the revised line.
 We can save the Command window dialog with the diary command.

diary filename
 We can clear the Command window with the clc command.
 We can close MATLAB with the quit (or) exit command.

Command History:
This window lists the commands typed in so far. We can re-execute a
command from this window by double clicking or dragging the command into the
Command window.

Fig(4)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 6


MATLAB Elementary course

Working space Window:

The Workspace window lists variables that we have either entered or


computed in our MATLAB session.

The command who (or) whos lists the variables currently in the
workspace. Try typing whos we should see a list of variables including A, B and C,
with their type and size. A variable or function can be cleared from the workspace
with the command clear variable name or by right clicking the variable in the
Workspace editor and selecting Delete. The command clear alone clears all variables
from the workspace.

Fig(5)

When you log out or exit MATLAB, all variables are lost. However, invoking
the command save before exiting causes all variables to be written to a machine-
readable file named matlab.mat in the current working directory. When you later re-
enter MATLAB, the command load will restore the workspace to its former state.
Commands save and load take file names and variable names as optional
arguments.

Visualization Window:
The Visualization Window is generates when we plot any diagram
using MATLAB commands.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 7


MATLAB Elementary course

Fig(6)

Help Window:
This window is the most useful window for MATLAB users.
Select Help ► MATLAB .
The Help window has most of the features we would see in any web
browser (clickable links, a back button, and a search engine, for example). The
Help Navigator on the left shows where you are in the MATLAB online
documentation. Online Help sections are referred to as
Help: MATLAB: Getting Started: Introduction.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 8


MATLAB Elementary course

Fig(8)

We can also use the help command, typed in the Command window. For
example, the command help det will give information about the
‘determent function’ det.
Moreover we can get help of related commands shown following fig(8).

Fig(9)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 9


MATLAB Elementary course

We have now seen most of MATLAB’s windows and what they can do. Now take
a look at how we can use MATLAB to work on variables and other data types.
VARIABLES AND ASSIGNMENTS
MATLAB variables are created when they appear on the left of an equal
sign. The general statement
>> Variable = expression
Creates the “variable” and assigns to it the value of the expression on the
right hand side.
Variables in MATLAB are limited to 31 characters and can contain upper and
lowercase letters, any number of ‘_’ characters, and numerals.
They may not start with a numeral. MATLAB is case sensitive ‘A‘and ‘a’ are
different variables.
The following are valid/invalid MATLAB variable assignments

Fig(10)
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 10
MATLAB Elementary course

We can make very general assignments for symbolic variables by using the
commands sym, syms and then manipulate them. For example
>>syms x y
>> a=(x+y)*(x-y)/(2*x+2*y) <Enter>
a=
((x + y)*(x - y))/(2*x + 2*y)

Note: To clear the value of the variable, give command clear a

Types of Variables:
Scalar Variables
Vector Variables(Array)
Matrices
Strings

Scalar Variables:
A variable with one row and one column is called scalar variable.

(i.e The size of a variable is 1x1)

Fig(11)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 11


MATLAB Elementary course

 Vector Variable(Array):
A variable with many rows and columns is called vector variable.
A vector is an ordered list of numbers. We can enter a vector of any length in
MATLAB by typing a list of numbers, separated by commas or spaces, inside
square brackets.
Example:
>> A= [1 2 3 4 5 6 7 8 9] <Enter>
A=

1 2 3 4 5 6 7 8 9
>> B= [1, 2, 3, 4, 5, 6, 7, 8, 9] <Enter>
B=

1 2 3 4 5 6 7 8 9

More points about to create a vector:


 Suppose we want to create a vector of values running from j to k
without typing each element then we can use commands
colon(j , k) or simply j:k (The notation j:k is used to represent a vector of numbers
running from j to k in increments of 1)
Suppose A=j:k (or) A=colon(j,k) is the same as A=[j ,j+1,j+2,……..j+k]

A=[j j+1 j+2 ………j+k] if j<k


Note: A=j:k (or) A=colon(j,k)=
Empty if j >k

Example:
Suppose we want create a vector from 1 to 15
>> A=1:15 <Enter>

A=

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

>> B=colon(1,15) <Enter>

B=

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

>> C=15:1 (here j > k) <Enter>

C=

Empty matrix: 1-by-0

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 12


MATLAB Elementary course

 Suppose we want to create a vector of values running from j to k in


increment/decrements of ‘i’. Then we can use commands
colon (j, i, k) or simply j:i:k.
Suppose A=colon (j, i ,k) (or) A=j:i:k is the same as
( )
A=[j , j+i , j+2i , j+3i ,………..j+mi] where m=

Note:
A=[j , j+i , j+2i, ……,j+mi] if j<k and i>0
A=[j, j-i , j-2i ,………., j-mi] if j >k and i<0
A=j:i:k= Empty if i=0
Empty if i>0 and j>k
Empty if i=0 and j<k

Example:

>>A=1:2:20 %increment by 2

A=

1 3 5 7 9 11 13 15 17 19

>> B=-1:0.4:1 %increment by 0.4

B=

-1.0000 -0.6000 -0.2000 0.2000 0.6000 1.0000

>> C=10:-1:1 %decrement by 1

C=

10 9 8 7 6 5 4 3 2 1

>> D=10:1:2

D=

Empty matrix: 1-by-0


 Suppose we want generate a row vector of N equally spaced of points
between X1 and X2 with help of MATLAB function linspace
Syntax
linspace(X1,X2) % generates a row vector of 100 linearly
equally spaced points between X1 and X2.
linspace(X1,X2,N) % generates N points between X1 and X2.
For N = 1, linspace returns X2.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 13


MATLAB Elementary course

Examples:
>> linspace(1,2,9)

ans =

1.0000 1.1250 1.2500 1.3750 1.5000 1.6250 1.7500 1.8750


2.0000

 We can construct a vector with all entries are primes from 2 to ‘n’
using the function primes(n)
Example

>> A=primes (25)

A=

2 3 5 7 11 13 17 19 23

 The elements of the vector A can be extracted as A(1), A(2), A(3) etc.

Example
>> A=1:100;
>> A(3)

ans =

>> A(25)

ans =

25

 To change the vector A from a row vector to a column


use A’ (or) Use A(:)

Example
>> A=1:3

A=

1 2 3

>> A(:)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 14


MATLAB Elementary course

ans =

1
2
3
 The function size(A) is gives size of vector A, length(A) is gives
length of the vector A and is equivalent to MAX(SIZE(A))
Example:

>> A=primes(100); <Enter>


>> size(A)

ans = %size of A is 1-by-25

1 25

>> length(A)

ans = %length of A is 25 (or) Maximum size of A

25

>> B=1:2:2000; %Odd numbers from 1 to 2000


>> C=B(:); %Changing row to column
>> size(B)

ans= %size of B is 1-by-1000


1 1000

>> size(C)

ans = %size of c is 1000-by-1

1000 1

>> length(C) %Maximum size of C is 1000

ans =

1000

>> C=[1 2 3 4;5 6 7 8;9 10 11 12]

C= %here C is a matrix

1 2 3 4
5 6 7 8
9 10 11 12

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 15


MATLAB Elementary course

>> size(C)

ans = %the size of C is 3-by-4

3 4

>> length(C) %Maximum size of C is 4

ans =

4
 Matrices :

To construct a matrix into MATLAB we must


 Begin with a square bracket [
 Separate elements in a row with commas or spaces
 Use a semicolon ; to separate rows
 End the matrix with another square bracket ]

Example:
>> A=[1 2 3;4 5 -6;-7 8 9] %separated elements in row with spaces
A=
1 2 3
4 5 -6
-7 8 9
>> A=[1,2,3;4,5,-6;-7,8,9] %separated elements in row with commas
A=
1 2 3
4 5 -6
-7 8 9
>> A=[1 2 3 %separated elements in row/column with
-4 5 -6 space and without semicolon ;
-7 8 9]
A=
1 2 3
-4 5 -6
-7 8 9

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 16


MATLAB Elementary course

More Points about to construct Matrix:


Matrices can be generated in several ways. Many elementary matrices can
be constructed directly with following MATLAB functions

 zeros (m,n) % Produces an m-by-n matrix of zeros


 zeros(n) % Produces an n-by-n matrix of zeros
 ones(m,n) % Produces an m-by-n matrix of ones
 one(n) % Produces an n-by-n matrix of ones
 eye (m,n) % Produces an m-by-n Identity matrix
 eye(n) % Produces an n-by-n Identity
matrix
 repmat %Replicate and tile array
 rand %Uniformly distributed random
numbers
 randn %Normally distributed random
numbers
 : %Regularly spaced vector and index into

Examples:
>> A=zeros(3,4) %constructing 3-by-4 matrix of zeros
A=
0 0 0 0
0 0 0 0
0 0 0 0
>> B=zeros(4) %constructing 4-by-4 matrix of zeros
B=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> C=ones(2,3) %constructing 2-by-3 matrix of ones
C=
1 1 1
1 1 1

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 17


MATLAB Elementary course

>> D=ones(5) %constructing 5-by-5 matrix of ones


D=
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>> E=eye(2,4) %constructing 2-by-4 Identity matrix
E=
1 0 0 0
0 1 0 0
>> E=eye(3) %constructing 3-by-3 Identity matrix
E=
1 0 0
0 1 0
0 0 1

 Suppose we want construct a n-by-n scalar matrix whose diagonal elements


are ‘c ’ .With A defined by A=eye(n)
We may create B=c *A
For example

>> B=2*eye(3) <Enter>

B=
2 0 0
0 2 0
0 0 2

>> B=-pi*eye(3) <Enter>

B=
-3.1416 0 0
0 -3.1416 0
0 0 -3.1416

 Matrices can be constructed in block form. With B defined by B = [1 2; 3 4],


we may create

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 18


MATLAB Elementary course

>> B=[A, zeros(2);ones(2),A] % A as first entry, zeros(2) as second entry, ones(2)


as 3rd entry, again A as 4th entry
B=
% created B as 4-by-4 matrix
1 2 0 0
3 4 0 0
1 1 1 2
1 1 3 4

 Diagonal matrices and diagonal of matrix can be defined using the


command diag.

Syntax

X = diag(v,k)
X = diag(v, k) when v is a vector of n components, returns a square
matrix X of order n+abs(k), with the elements of v on the kth diagonal.

k = 0 represents the main diagonal


X=diag(v,k) = k > 0 above the main diagonal
k < 0 below the main diagonal.

 X = diag(v) % Is same as diag(v,0)


 v = diag(X,k) % A column vector v formed from the elements of
the kth diagonal of X
 v = diag(X) %same as above with k= 0

Example:
>> v=[1 2 3 4 5 6]
v=
1 2 3 4 5 6
>> X=diag(v) <Enter>
X=
1 0 0 0 0 0
0 2 0 0 0 0
0 0 3 0 0 0
0 0 0 4 0 0
0 0 0 0 5 0
0 0 0 0 0 6

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 19


MATLAB Elementary course

>> X=diag(v,3)
X= %created 9-by-9 matrix with the elements of v
On the 3rd diagonal.
0 0 0 1 0 0 0 0 0
0 0 0 0 2 0 0 0 0
0 0 0 0 0 3 0 0 0
0 0 0 0 0 0 4 0 0
0 0 0 0 0 0 0 5 0
0 0 0 0 0 0 0 0 6
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
>> X=diag(v,-3)
X=
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0
0 0 0 0 5 0 0 0 0
0 0 0 0 0 7 0 0 0

>> X=diag(-5:1:5) <Enter>

X=
-5 0 0 0 0 0 0 0 0 0 0
0 -4 0 0 0 0 0 0 0 0 0
0 0 -3 0 0 0 0 0 0 0 0
0 0 0 -2 0 0 0 0 0 0 0
0 0 0 0 -1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 3 0 0
0 0 0 0 0 0 0 0 0 4 0
0 0 0 0 0 0 0 0 0 0 5

>> v=diag(X) <Enter>


v=
-5
-4
-3
-2
-1
0
1
2
3
4
5
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 20
MATLAB Elementary course

 Block diagonal matrices can be defined using the command blkdiag, which
its easier than using the square bracket notation.
Example:

>> A=blkdiag(1,2,3,4,5,6,7,8,9) <Enter>

A=

1 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0
0 0 0 0 5 0 0 0 0
0 0 0 0 0 6 0 0 0
0 0 0 0 0 0 7 0 0
0 0 0 0 0 0 0 8 0
0 0 0 0 0 0 0 0 9

>> A=[1 2;3 4];C=[5 6;7 8]; <Enter>

>> B=blkdiag(A,C) <Enter>

B=

1 2 0 0
3 4 0 0
0 0 5 6
0 0 7 8
>> D=blkdiag(A, A, C, C) <Enter>
D= %created D as 8-by-8 block matrix

1 2 0 0 0 0 0 0
3 4 0 0 0 0 0 0
0 0 1 2 0 0 0 0
0 0 3 4 0 0 0 0
0 0 0 0 5 6 0 0
0 0 0 0 7 8 0 0
0 0 0 0 0 0 5 6
0 0 0 0 0 0 7 8

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 21


MATLAB Elementary course

 We can constructed "tiled" block matrices with the function repmat


syntex
repmat (A , m, n) %creates a block m-by-n matrix in which
each block is a copy of A.

repmat(A,n) % it default

Examples:

>> A=[-3 4;5 0] <Enter>

A=
-3 4
5 0

>> B=repmat(A,2,3) <Enter>

B=

-3 4 -3 4 -3 4
5 0 5 0 5 0
-3 4 -3 4 -3 4
5 0 5 0 5 0

 We can convert a vector to a matrix

Vector Matrix

•A=[a1,a2,a3,...............an]
•lengh(A)=n
step-1 •n=rxs

•B=zeros(r,s) (or) any r-by-s matrix


•B(:)=A
setp-2 •B=[aij]rxs

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 22


MATLAB Elementary course

Let A=1:2:20; %odd numbers from 1 to 19


.

>> A=1:2:20; % length(A)=10, then we can construct a matrix of size is 2-by-5


(or)5-by-2 with all entries are odd number from 1 to 19

>> B=zeros(2,5); <Enter>


>> B(:)=A <Enter>

B=

1 5 9 13 17
3 7 11 15 19

>>B=zeros(5,2); <Enter>
>> B(:)=A <Enter>

B=

1 11
3 13
5 15
7 17
9 19

>> A=primes(25); <Enter>


>> B=zeros(3); <Enter>
>> B(:)=A <Enter>

B=

2 7 17
3 11 19
5 13 23

>> C=zeros(5,5); <Enter>


>> C(:)=1:25

C=

1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 23


MATLAB Elementary course

Exercise.1.
1) Create an array of size 25-by-1 which has all prime numbers

2) Construct following Matrix using MATLAB function.

-1 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 3 0 0 0 0 0
A= 0 0 0 0 4 0 0 0 0
0 0 0 0 0 5 0 0 0
0 0 0 0 0 0 6 0 0
0 0 0 0 0 0 0 7 0
0 0 0 0 0 0 0 0 8

3) How many prime numbers up to 10000000?

4) Construct following Matrix B with help of A

A= -2 3 ;
1 4

0 5 -2 3
B= 3 6 1 4
-2 3 -1 4
1 4 2 5

5) Construct any 10-by-10 scalar matrix.


b c a
6) Construct A= d e f and find 2A+3I.
g h i
7) Let B defined as repmat(A,4,8) then what is order of B? Where A is 3-by-3 order.

8) Suppose A,B,C are 3-by-3, 2-by-2, 2-by-2 size of matrices respectively, D defined as
[repmat(B,2,2), A; C , eye(2)] than what is the output of D?

9) Using MATLAB functions eye, ones, zeros construct following matrix.


1 1 1 1 1 0 1 0
1 1 1 1 0 1 0 1
1 1 1 1 1 0 1 0
A= 1 1 1 1 0 1 0 1
1 1 1 1 1 0 1 0
1 1 1 1 0 1 0 1
1 1 1 1 1 0 1 0
1 1 1 1 0 1 0 1

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 24


MATLAB Elementary course

10) Construct following with help function diag.

-2 1 0 0 0
1 -1 1 0 0
0 1 0 1 0
0 0 1 1 1
0 0 0 1 2

11) Construct a matrix whose entries are from 10 to 75 which are divisible by 5.
12) Construct a matrix whose entries are from 1 t0 100 which are divisible by 2 and 3.
13) Construct a 5-by-7 matrix whose entries all are primes.
14) What is the order of repmat(repmat(eye(5),4,5),5,4)?
15) Construct an array with entries are primes between 100 to200 .

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 25


MATLAB Elementary course

 MATLAB provides some following special matrices

 compan % Companion matrix


 hadamard % Hadamard matrix
 hankel % Hankel matrix
 hilb % Hilbert matrix
 magic % Magic square
 pascal % Pascal matrix
 toeplitz % Toeplitz matrix
 vander % Vandermonde matrix
 wilkinson % Wilkinson's eigenvalue test matrix
 gallery % Large collection of test matrices
 rosser % Classic symmetric eigenvalue test matrix

 Companion Matrix:

Syntax:

A = compan(u)
Description:

A = compan(u) returns the corresponding companion matrix whose first


row is -u(2:n)/u(1),where u is a vector of polynomial coefficients. The
eigenvalues of compan(u) are the roots of the polynomial.

Example:
>> syms x; %symbolic variable
>> p(x)=(x-2)*(x-3)*(x-4); %initializing polynomial p(x)
>> p(x)=expand(p(x))

p(x) =

x^3 - 9*x^2 + 26*x - 24

>> u=[1 -9 26 -24]; %initializing coefficients of p(x)


>> A=compan(u)

A= %Companion matrix of u

9 -26 24
1 0 0
0 1 0

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 26


MATLAB Elementary course

>> r=eig(A) % eigen values of A

r= %result eigenvalues are roots of the


Polynomial p(x)
4.0000
3.0000
2.0000

 Magic Matrix:
magic Magic square.

magic(N) % An N-by-N matrix constructed from the integers.

1 through N^2 with equal row, column, and diagonal sums. Produces
valid magic squares for all N > 0 except N = 2.
The value of the characteristic sum for a magic square of order n is
sum(1:n^2)/n

Syntax:
M = magic(n)

Description:
M = magic(n) returns an n-by-n matrix constructed from the integers 1
through n^2 with equal row and column sums. The order n must be a scalar
greater than or equal to 3.

Note: The value of the characteristic sum for a magic square of order n is
(1+2+3+4+……+n2)/n

Example:
>> A=magic(3) %constructing 3-by-3 magic matrix

A=

8 1 6 % sum of all rows and column are equal to 15


3 5 7
4 9 2

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 27


MATLAB Elementary course

 Toeplitz Matrix:
 The toeplitz function constructs a Toeplitz matrix.
 One for which the elements down each diagonal are constant.
 To construct a Toeplitz matrix, specify the first column and first row
Example :
»A= toeplitz( [1 o -1 -2] ,[1 2 4 8]) <Enter>

A=
1 2 4 8
0 1 2 4
-1 0 1 2
-2 -1 0 1
 Hankel Matrix:
 The hankel function constructs a Hankel matrix.
 One for which the elements down each ant diagonal are constants
 For a Hankel matrix it is the first column and last row that are
specified
»A= hankel ( [3 1 2 0] , [0 -1 -2 -3]) <Enter>

A=
3 1 2 0
1 2 0 -1
2 0 -1 -2
0 -1 -2 -3
 Gallery:
The function gallery provides access to a large collection of test matrices
Using command help gallery we can get following matrices.

 binomial % Binomial matrix -- multiple of involutory matrix.


 cauchy % Cauchy matrix.
 chebspec %Chebyshev spectral differentiation matrix.
 chebvand % Vandermonde-like matrix for the Chebyshev
polynomials.
 chow % Chow matrix -- a singular Toeplitz lower Hessenberg
matrix.
 circul %Circulant matrix.
 clement %Clement matrix -- tridiagonal with zero diagonal entries.
 compar % Comparison matrices.
 condex %Counter-examples to matrix condition number
estimators.
 cycol %Matrix whose columns repeat cyclically.
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 28
MATLAB Elementary course

 dorr %Dorr matrix -- diagonally dominant, ill-conditioned,


tri diagonal. (One or three output arguments, sparse)
 dramadah %Matrix of ones and zeroes whose inverse has large integer
entries
 fiedler %Fiedler matrix -- symmetric.
 forsythe % Forsythe matrix -- a perturbed Jordan block.
 frank % Frank matrix -- ill-conditioned eigenvalues.
 gcdmat % GCD matrix.
 gearmat % Gear matrix.
 grcar %Grcar matrix -- a Toeplitz matrix with sensitive
eigenvalues.
 hanowa %Matrix whose eigenvalues lie on a vertical line in the
complex plane

 house % Householder matrix. (Three output arguments)


integer data Array of arbitrary data from uniform
distribution on specified range of integers
 invhess % Inverse of an upper Hessenberg matrix.
 invol %Involutory matrix.
 ipjfact %Hankel matrix with factorial elements. (Two output
arguments)
 jordbloc %Jordan block matrix.
 kahan %Kahan matrix -- upper trapezoidal.
 kms %Kac-Murdock-Szego Toeplitz matrix.
 krylov %Krylov matrix.
 lauchli % Lauchli matrix -- rectangular.
 lehmer %Lehmer matrix -- symmetric positive definite.
 leslie %Leslie matrix.
 lesp %Tridiagonal matrix with real, sensitive eigenvalues.
 lotkin % Lotkin matrix.
 minij % Symmetric positive definite matrix MIN(i,j).
 moler % Moler matrix -- symmetric positive definite.
 neumann % Singular matrix from the discrete Neumann problem
(sparse).
 normaldata %Array of arbitrary data from standard normal distribution
 orthog % Orthogonal and nearly orthogonal matrices.
 parter %Parter matrix -- a Toeplitz matrix with singular values
near PI.
 pei % Pei matrix.
 poisson %Block tridiagonal matrix from Poisson's equation (sparse).
 prolate %Prolate matrix -- symmetric, ill-conditioned Toeplitz matrix.
 qmult %Pre-multiply matrix by random orthogonal matrix.
 randcolu %Random matrix with normalized cols and specified singular
values.
 randcorr % Random correlation matrix with specified eigenvalues.
 randhess %Random, orthogonal upper Hessenberg matrix.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 29


MATLAB Elementary course

 randjorth % Random J-orthogonal (hyperbolic, pseudo-orthogonal)


matrix.
 rando %Random matrix with elements -1, 0 or 1.
 randsvd %Random matrix with pre-assigned singular values and
specified bandwidth.
 redheff %Matrix of 0s and 1s of Redheffer.
 riemann % Matrix associated with the Riemann hypothesis.
 ris % Ris matrix -- a symmetric Hankel matrix.
 sampling %Non- symmetric matrix with integer, ill conditioned
Eigen values.
 smoke % Smoke matrix -- complex, with a "smoke ring"
pseudo spectrum.
 toeppd %Symmetric positive definite Toeplitz matrix.
 toeppen % Pentadiagonal Toeplitz matrix (sparse).
 tridiag %Tridiagonal matrix (sparse).
 triw % Upper triangular matrix discussed by Wilkinson and
others. Uniform data Array of arbitrary data from
standard uniform distribution
 wathen %Wathen matrix -- a finite element matrix
(sparse, random entries).
 wilk % Various specific matrices devised/discussed by Wilkinson.
(Two output arguments)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 30


MATLAB Elementary course

Accessing Submatrices:
Colon notation can be used to access submatrices of a matrix.
Commands:
Let A be any m-by-n matrix

 A(j,k) %is the jth , kth entry of A

 A ( :, j ) % is the jth column of A

 A (i, :) % is the ith row of A

 A (: , :) % is the equivalent two-dimensional array. For


matrices the is the same as A.

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

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

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

 A(i,j,k,:) % is a vector in four-dimensional array A. The vector


Includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on.

 A (i:j ,r:s) % is the ith row to jth row and rth column to sth
column
 A (:) % is all the elements of A, regarded as a single
column. On the left side of an assignment
statement, A(:) fills A, preserving its shape from
before. In this case, the right side must contain
the same number of elements as A.

 A (primes(n), :) % is the prime rows of A

 A (: ,primes(n)) % is the prime columns of A

 Deleting rows and columns:


Use the colon operator and the empty array to delete entire rows or columns.

 A(i,:)=[ ] %Deleting ith row


 A(:, j)=[ ] %Deleting jth column
 A(i:j , :)=[ ] %Deleting ith tojth row
 A(: ,r:s)=[ ] %Deleting rth to sth columns
 We can’t delete a single element from a matrix while keeping it a matrix
A(i , j)=[ ] %Error
 A(j:d:k)=[ ] % Deleting a sequence of elementsA(j) ,A(j+d),…… A(k)
from a matrix and reshape the remaining elements
into a row vector.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 31


MATLAB Elementary course

 Insert a matrix ‘B’ in A as a submatrix:

Setp-1 step-2 step-3


• Let A be any • Suppose we want to • A(u,v)=B
m-by-n matrix insert B in A as ith,jth....kth
• B be any t-by-s rows , pth, qth ..... rth
marix where coloumns.......
t,s<m,n • chose two vectros
u=[i, j.......k]
v=[ p,q....t]

Examples:
Let a 5-by5 matrix A

1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25

>> A(2,4) <Enter>

ans =

17

>> A(3,:) <Enter>

ans =

3 8 13 18 23

>> A(:,3) <Enter>

ans =

11
12
13
14
15

>> A(2:4) <Enter>

ans =

2 3 4

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 32


MATLAB Elementary course

>> A(2:4,:) <Enter>

ans =

2 7 12 17 22
3 8 13 18 23
4 9 14 19 24

>> A(:,2:4) <Enter>

ans =

6 11 16
7 12 17
8 13 18
9 14 19
10 15 20

>> A(2:4,2:4) <Enter>

ans =

7 12 17
8 13 18
9 14 19

>> A ([1,2,3],:) <Enter>

ans =

1 6 11 16 21
2 7 12 17 22
3 8 13 18 23

>> A(:,:,3) <Enter>


Index exceeds matrix dimensions.

>> A(:,:,2) <Enter>


Index exceeds matrix dimensions.

>> A(primes(5),:) <Enter>

ans =

2 7 12 17 22
3 8 13 18 23
5 10 15 20 25

>> A(:,primes(5)) <Enter>

ans =

6 11 21
7 12 22
8 13 23
9 14 24
10 15 25
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 33
MATLAB Elementary course

>> v=[3,5] ; u=[1,5] ; <Enter> 1 2 3 4 5

>> A(v,u)
1
ans =
2
3 23 3

5 25 4
5

>> A(1,:)=[ ] <Enter>

A= %Deleting 1-row
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25

>> A(:,2)=[ ] <Enter>

A= %Deleting 2-column

1 11 16 21
2 12 17 22
3 13 18 23
4 14 19 24
5 15 20 25

>> A(1:2:3,:)=[ ] <Enter>

A= %Deleting 1-row,3-row

2 7 12 17 22
4 9 14 19 24
5 10 15 20 25

>> A(:,[1,2,5])=[ ] <Enter>

A= %Deleting 1,2,5 columns


11 16
12 17
13 18
14 19
15 20

>> v=[3 5];u=[1 5]; <Enter>


>> A(v,u)=[ ]

Subscripted assignment dimension mismatch.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 34


MATLAB Elementary course

>> A(2,3)=[ ] <Enter> %Single entry can’t be delete


Subscripted assignment dimension mismatch. %ERROR

>> A(2:2:10)=[ ] <Enter>

A=
1 3 5 7 9 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
% Deleted 2nd , 4th ,6th,8th, 10th entries ……..remaining entries are arranged as row vector
1 11 16 21
7 12 17 22
3 13 18 23
9 14 19 24
5 15 20 25

>> A(1:25)=[ ] <Enter>

A= %all entries are deleting


Empty matrix: 1-by-0
>> A(primes(25))=[ ] <Enter>

A=
1 4 6 8 9 10 12 14 15 16 18 20 21 22 24 25

>> B=2*ones(3);
>> A(3:5,3:5)=B %inserting B in A as a submatrix
A=
1 6 11 16 21
A
2 7 12 17 22
3 8 2 2 2
B
4 9 2 2 2
5 10 2 2 2

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 35


MATLAB Elementary course

Exercise -2
1) Let A be a 5-by-8 matrix
11 16 21 26 31 36 41 46
12 17 22 27 32 37 42 47
13 18 23 28 33 38 43 48
14 19 24 29 34 39 44 49
15 20 25 30 35 40 45 50

Construct following sub matrices of A.

a) 12 17 22 27 32 37 42 47
15 20 25 30 35 40 45 50

b) 36 16
37 17
38 18
39 19
40 20

c) 30 35 40 45 50
29 34 39 44 49
28 33 38 43 48

d) 36 31 26 21
37 32 27 22
38 33 28 23

e) 39 34 29 24
38 33 28 23

f) 21 41 46
24 44 49
25 45 50

g) 17 22 32
18 23 33
20 25 35

2) Let A be a 7-by -8 matrix


1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Then construct following matrices using colon (:)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 36


MATLAB Elementary course

a) 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

b) 1 1 1 1 0 0 1 1
1 1 1 0 1 0 1 1
1 1 1 0 0 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

c) 1 1 1 1 1 1 1 1
1 1 1 4 7 1 1 1
1 1 2 5 8 1 1 1
1 1 3 6 9 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

d) 1 1 1 1 1 1 1 1
2 2 2 -1 -1 2 2 2
1 1 1 -1 -1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

e) 1 4 1 1 20 36 1 1
1 16 1 1 32 48 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 8 1 1 24 40 1 1
1 1 1 1 1 1 1 1
1 12 1 1 28 44 1 1

f) 1 4 1 1 20 36 1 1
1 12 0 0 28 44 0 1
1 1 1 1 1 1 1 1
1 1 0 0 1 1 0 1
1 8 1 1 24 40 1 1
1 1 0 0 1 1 0 1
1 16 1 1 32 48 1 1

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 37


MATLAB Elementary course

3) With the help flowing picture give the commands to construct following pictures.

a)

b)

c)

d)

e)

f)

g)

h)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 38


MATLAB Elementary course

1) Using ‘colon’ notenation and ‘char’ print ZYXWVU…………A.


2) Using ‘colon’ notation and ‘char’ print zyxwvu……..a.
3) Using ‘colon’ notation and ‘char’ print ACEGIKMOQSUWY.
4) Using ‘primes’ and ‘char’ ,print BCEGKMQSW
5) Using ‘char’ print VIVEKANANDA GOVT DEGREE COLLEGE.
6) Using matrices ‘ones’,’zeros’ ,’eye’ and ‘colon’,’char’, ‘double’ print following
pictures.

AAAAAAAAAA
AAAAAAAAAA AAAAAA
AAAAAAAAAA BB BBBB
AAAAAAAAAA CCCCC C
AAAAAAAAAA DDDDDD
AAAAAAAAAA E EE EE E
AAAAAAAAAA F FF FF F
AAAAAAAAAA
AAAAAAAAAA A
AAAAAAAAAA AA
AAA
A AAAA
A AAAAA
A AAAAAA
A AAAAAAA
A AAAAAAAA

ABCDE ##########
FGH I J # #
KLMNO # #
PQR ST # #
UVWXY # #
# #
AAABBB # #
AAABBB # #
AAABBB # #
CCC DDD ##########
CCC DDD
CCC DDD

AAAAAAAAAA
AAAAAAAA A
AAAAAA ABA
AAAA ABCBA
AA ABCDCBA
ABCDEDCBA

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 39


MATLAB Elementary course

Section-1
1. Perform the addition operation 7+9.
2. Perform the subtraction operation 16-10.
3. Perform the multiplication operation 2(9).
4. Perform the division operation 12/3.
5. Perform the division operation 12/5.
6. Perform the exponentiation operation 35+45.
7. Perform the exponentiation operation 3(-5).
8. Perform the exponentiation operation (-3)5+(-2)7.
9. Perform the exponentiation operation -35-27.
10. Compute the value of .(pi)2-3
11. Obtain the value of the smallest number that can be handled by MATLAB.
12. Perform the multiple operations 5+7-15.
13. Perform the multiple operations 6(7)+4.
14. Perform the multiple operations 6(7+4).
15. Perform the multiple operations 4.5 + (15/2).
16. Perform the multiple operations (4.5 + 15)/2.
17. Perform the multiple operations (15 – 4 + 12)/5 – 2(74)/100.
18. Perform the multiple operations (15 – 4) + 12/5 – (2(7))4/100.
19. Define the number 2/3 as a symbolic number.
20. Perform the fraction addition (2/3) + (3/4) numerically.
Section-2
Solve all the exercises using MATLAB. All the needed MATLAB commands for these
exercises were presented in this exercises. Note that Exercises 21-27 require the use of the
MATLAB Symbolic Math Toolbox.
1. Perform the operation 2(3)+7 and store the result in the variable w.
2. Define the three variables a, b, and c equal to 4, -10, and 3.2, respectively.
3. Define the two variables y and Y equal to 10 and 100. Are the two variables identical?
4. Let x = 5.5 and y = -2.6. Calculate the value of the variable z = 2x-3y.
5. In Exercise 4 above, calculate the value of the variable w = 3y – z + x/y.
6. Let r = 6.3 and s = 5.8. Calculate the value of the variable final defined by final = r + s- rs.
7. In Exercise 6 above, calculate the value of the variable this_is_the_result defined by
this_is_the_result = r2 – s2.
8. Define the three variable width, Width, and WIDTH equal to 1.5, 2.0, and 4.5,
respectively. Are these three variables identical?
9. Write the following comment in MATLAB: This line will not be executed.
10. Assign the value of 3.5 to the variable S then add a comment about this assignment on
the same line.
11. Define the values of the variables y1 and y2 equal to 7 and 9 then perform the
calculation y3 =y1 – y2/3. (Note: 2 in the formula is a subscript and should not be divided by
3).
MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 40
MATLAB Elementary course

12. Perform the operation 2m – 5. Do you get an error? Why?


13. Define the variables cost and profit equal to 175 and 25, respectively, then calculate the
variable sale_price defined by sale_price = cost + profit.
14. Define the variable centigrade equal to 28 then calculate the variable fahrenheit
defined by fahrenheit = (centigrade*9/5) + 32.
15. Use the format short and format long commands to write the values of 14/9 to four
decimals and sixteen digits, respectively.
16. Perform the who command to get a list of the variables stored in this session.
17. Perform the whos command to get a list of the variables stored in this session along with
their details.
18. Clear all the variables stored in this session by using the clear command.
19. Calculate both the area and perimeter of a rectangle of sides 5 and 7. No units are used
in this exercise.
20. Calculate both the area and perimeter of a circle of radius 6.45. No units are used in
this exercise.
21. Define the symbolic variables x and z with values 4/5 and 14/17.
22. In Exercise 21 above, calculate symbolically the value of the symbolic variable y defined
by y =2x – z.
23. Calculate symbolically the area of a circle of radius 2/3 without obtaining a numerical
value. No units are used in this exercise.
24. Calculate symbolically the volume of a sphere of radius 2/3 without obtaining a
numerical value. No units are used in this exercise.
25. In Exercise 23 above, use the double command to obtain the numerical value of the
answer.
26. In Exercise 24 above, use the double command to obtain the numerical value of the
answer
Section-3
1. Store the vector [2 4 -6 0] in the variable w.
2. In Exercise 1 above, extract the second element of the vector w.

3. In Exercise 1 above, generate the vector z where z=

4. In Exercise 3 above, extract the fourth element of the vector z.


5. In Exercise 3 above, extract the first three elements of the vector z.
6. In Exercise 3 above, find the length of the vector z.
7. In Exercise 3 above, find the total sum of the values of the elements of the vector z.
8. In Exercise 3 above, find the minimum and maximum values of the elements of the
vector z.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 41


MATLAB Elementary course

9. Generate a vector r with real values between 1 and 10 with an increment of 2.5.
10. Generate a vector s with real values of ten numbers that are equally spaced between 1
and 100.
11. Form a new vector by joining the two vectors [9 3 -2 5 0] and [1 2 -4].
12. Form a new vector by joining the vector [9 3 -2 5 0] with the number 4.
13. Add the two vectors [0.2 1.3 -3.5] and [0.5 -2.5 1.0].
14. Subtract the two vectors in Exercise 13 above.
15. Try to multiply the two vectors in Exercise 13 above. Do you get an error message? Why?
16. Multiply the two elements in Exercise 13 above element by element.
17. Divide the two elements in Exercise 13 above element by element.
18. Find the dot product of the two vectors in Exercise 13 above.
19. Try to add the two vectors [1 3 5] and [3 6]. Do you get an error message? Why?
20. Try to subtract the two vectors in Exercise 20 above. Do you get an error message?
Why?
21. Let the vector w be defined by w = [0.1 1.3 -2.4]. Perform the operation of scalar
addition 5+w.
22. In Exercise 22 above, perform the operation of scalar subtraction -2-5w.
23. In Exercise 22 above, perform the operation of scalar multiplication 1.5w.
24. In Exercise 22 above, perform the operation of scalar division w/10.
25. In Exercise 22 above, perform the operation 3 – 2w/5.
26. Define the vector b by b = [0 pi/3 2pi/3 pi]. Evaluate the three vectors sin b , cosb , and
tan b(element by element).
27. In Exercise 26 above, evaluate the vector eb (element by element).

28. In Exercise 26 above, evaluate the vector √ (element by element).


29. Try to evaluate the vector 3b. Do you get an error message? Why?
30. Perform the operation in Exercise 29 above element by element?
31. Generate a vector of 1’s with a length of 10 elements.
32. Generate a vector of 0’s with a length of 10 elements.
33. Sort the elements of the vector [0.35 -1.0 0.24 1.30 -0.03] in ascending order.
34. Generate a random permutation vector with 5 elements.
35. For the vector [2 4 -3 0 1 5 7], determine the range, mean, and median.
36. Define the symbolic vector x = [r s t u v].
37. In Exercise 36 above, perform the addition operation of the two vectors x and
[1 0 -2 3 5] to obtain the new symbolic vector y.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 42


MATLAB Elementary course

38. In Exercise 37 above, extract the third element of the vector y.


39. In Exercise 37 above, perform the operation 2*x/7 + 3*y.
40. In Exercise 37 above, perform the dot products x*y’ and y*x’. Are the two results the
same?Why?
41. In Exercise 37 above, find the square root of the symbolic vector x+y.

Section-4
1. 1+2+3+…………………………+100 is equal to
2. 11+22+32+----------------+1002 is equal to
3. 1+23+33+-----------------+1003 is equal to
4. 1+24+34+------------------+1004 is equal to
5. 11+22+33+------------------+1010 is equal to?
6. 110+29+38+47+56+65+74+83+92+101 is equal to?
7. Calculate Sum of first 100 even numbers .
8. Calculate sum of first 100 odd numbers.
9. 2+22+23+25+-------+215 is equal to?
10. 1-2+3-4+5-6+7-8+9-10 is equal to?
11. 1-2+3-4+5-6+7-8+----------+99-100 is equal to?
12. 1+1/2+1/3+1/4+------------+1/20 is equal to?

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 43


MATLAB Elementary course

Exercises
Solve all the exercises using MATLAB. All the needed MATLAB commands for these
exercises.were presented in this chapter. Note that Exercises 19-25 require the use of the
MATLAB Symbolic Math Toolbox.
1. Compute the square root of 10.
2. Compute the factorial of 7.
3. Compute the cosine of the angle 45 where 45 is in radians.
4. Compute the cosine of the angle 45 where 45 is in degrees.
5. Compute the sine of the angle of 45 where 45 is in degrees.
6. Compute the tangent of the angle 45 where 45 is in degrees.
7. Compute the inverse tangent of 1.5.
8. Compute the tangent of the angle . Do you get an error? Why?
9. Compute the value of exponential function e3 .
10. Compute the value of the natural logarithm ln 3.5 .
11. Compute the value of the logarithm log10 3.5 .
12. Use the MATLAB rounding function round to round the value of 2.43.
13. Use the MATLAB remainder function rem to obtain the remainder when dividing 5 by
4.
14. Compute the absolute value of -3.6.

15. Compute the value of the expression 1.5-2√6.7/5.


16. Compute the value of sin2 π + cos2 π .
17. Compute the value of log10 0. Do you get an error? Why?

18. Let x= and y = 2π. Compute the value of the expression 2sin x cos y .

19. Compute the value of √45 symbolically and simplify the result.

20. Compute the value of √45 numerically.


21. Compute the sine of the angle 45 (degrees) symbolically.
22. Compute the cosine of the angle 45 (degrees) symbolically.
23. Compute the tangent of the angle 45 (degrees) symbolically.
24. Compute the value of exp(π / 2) symbolically.
25. Compute the value of exp(π / 2) numerically.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 44


MATLAB Elementary course

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 45


MATLAB Elementary course

SIMPLE PROGRAMS

mkdir-make new
directory

mkdir(‘folder name’)

mkdir(‘rajesh’)

mkdir(‘9700201340’)

cd-change current
directory

cd(‘rajesh’)

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 46


MATLAB Elementary course

Section-1

1) Write program, which reads as input sides of a rectangle and prints its area.
2) Write program, which reads 2 numbers and prints the sum of square of the first and cube of
the second. (ex. input 5 3 output 52+33 =52.)
3) Write program to delete the last digit. (ex: input 13613 output 1361. input 324 output 32.)
4) Write program to delete last two digits.(ex: input 13613 output 136. input 324 output 4.)
5) Write program to print the second last digit. Input 23617 output 1.
6) Program to find the sum of last two digits. For above inputs output 1+3=4 and 2+4=6.
7) Write program to double the last digit. (ex. input 23613 output 23616. input 324 output 328.
(assume that last digit is less than 5)
8) Write program to delete the second last digit. (ex. input 23617 output 2367).
9) Write program to exchange last two digits. (ex. input 23617 output 23671.)
10) Write program to exchange last and third last digit. e.g. input 23617 output 23716.
11) Write program to double the second last digit. e.g. input 23613 output 23623. input 324
output 344. (assume that second last digit is less than 5)
12) Read two numbers. Find their product after exchanging last digits. Input 4270 and 153
output 640950 (4273x150). Input 348 and 31 output 12958 (341*38).
Section-2

1. Write program, which reads a, b and c as sides of a triangle and prints its are
[Hint: area=√ ( − )( − )( − ) where S = (a+b+c)/2] [sqrt(x) will find square root].
Input 5 7 10 output 16.24. ]
2. Write program, which reads a, b, c and d and finds distance between points
(a,b) and(c,d). input 3, 7, 11, 13 output 10.
3. Write program, which reads 6 numbers a, b, c, d, e and f. The program outputs the area
of the triangle whose end points are (a,b), (c,d) and (e,f). [Hint: use above two questions].
Input 7 3 11 3 7 6 output 6.
4. Write program, which reads a, b, and c. Let ax + by + c = 0 be equation of a line. The
program outputs the slope. Input 3 5 8 output -0.6.
5. Write program, which reads a, b, c, d and e and prints the distance between point (a,b)
and line cx+dy+e=0. [Hint: (ac+bd+e)/√(c2+d2).] input 6 7 3 4 2 output 9.6.
6. Write program, which reads a, b, and c. Let x2 + y2+ ax + by + c = 0 be equation of a
circle. Print its center and radius. Input 10, -6 and -2 then output is center (-5,3) and
radius 6. Here circle is x2+y2+10x-6y-2=0.
7. Write program, which reads a, b, c, p, q and r. Let ax + by + c = 0 and px + qy + r = 0 be
equations of lines. Print their point of intersection. Input 4 8 12 2 7 3 output (-5,1).
8. Write program, which reads a, b and c as sides of a triangle and prints the angle A in
degree and radian. Hint: a2 = b2 + c2 – 2bcCOS(A). [Hint: use acos. Example: input 13, 12, 5
output 90. input 10, 20, 17.32 output 30. input 7, 7, 7 output 60]
9. Write program, which reads h, k, r, and s. Let a circle has center (h,k) and radius r. Let
line x=s intersects the circle. The program, the chord length. Input 2 4 13 7 output 24.
[Hint: find distance of the line from the center].
10. Modify above program to find the area of the triangle formed by the points of
intersection and the center of the circle. Input 2 4 13 7 output 12x13=60.
11. Modify above program to output the points of intersection of the circle and the line.
Input 2 4 13 7 output (7,16) and (7,-8).
12. Read a, b, c, d, e, f, g, and h. Let ax+by+cz+d=0 be a plane and x2+y2+z2+ex+fy+gz+h=0
be a sphere. Find the area of circle of intersection of the

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 47


MATLAB Elementary course

MATHEMATICS FUNCTIONS
Trigonometric:
acos- Inverse cosine; result in radians
acosd- Inverse cosine; result in degrees Complex
acosh -Inverse hyperbolic cosine
acot- Inverse cotangent; result in radians abs -Absolute value and complex
acotd- Inverse cotangent result in degrees magnitude
acoth- Inverse hyperbolic cotangent angle -Phase angle
acsc- Inverse cosecant; result in radians complex -Construct complex data from real
acscd -Inverse cosecant; result in degrees and imaginary components
acsch- Inverse hyperbolic cosecant conj -Complex conjugate
asec- Inverse secant; result in radians cplxpair -Sort complex numbers into complex
asecd- Inverse secant; result in degrees conjugate pairs
asech- Inverse hyperbolic secant i -Imaginary unit
asin -Inverse sine; result in radians imag- Imaginary part of complex number
asind -Inverse sine; result in degrees isreal -Determine whether input is real
asinh- Inverse hyperbolic sine array
atan- Inverse tangent; result in radians j- Imaginary unitreal Real part of complex
atan2 -Four-quadrant inverse tangent number
atand -Inverse tangent; result in degrees Rounding and Remainder
atanh- Inverse hyperbolic tangent Ceil- Round toward infinity
cos -Cosine of argument in radians fix -Round toward zero
cosd- Cosine ofo argument in degrees floor- Round toward minus infinity
cosh -Hyperbolic cosine idivide- Integer division with rounding
cot -Cotangent of argument in radians option
cotd- Cotangent of argument in degrees mod- Modulus after division
coth- Hyperbolic cotangent rem- Remainder after division
csc -Cosecant of argument in radians round- Round to nearest integer
cscd -Cosecant of argument in degrees factor- Prime factors
csch -Hyperbolic cosecant factorial -Factorial function
hypot -Square root of sum of squares gcd -Greatest common divisor
sec- Secant of argument in radians isprime- Array elements that are prime
secd -Secant of argument in degrees numbers
sech- Hyperbolic secant lcm -Least common multiple
sin -Sine of argument in radians nchoosek-Binomial coefficient or all
sind -Sine of argument in degrees combinations
sinh- Hyperbolic sine of argument in perms- All possible permutations
radians primes -Generate list of prime numbers
tan -Tangent of argument in radians rat, rats -Rational fraction approximation
tand -Tangent of argument in degrees
tanh- Hyperbolic tangent
Exponential:
exp -Exponential
expm1 -Compute exp(x)-1 accurately for
small values of x
log -Natural logarithm
log10 -Common (base 10) logarithm
log1p -Compute log(1+x) accurately for
small values of x
log2 -Base 2 logarithm

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 48


MATLAB Elementary course

Forms of if-else
Relational Operators
(1) if ( condition )
do this ;
< Less than
end
<= Less than or equal to
> Greater than
(2) if ( condition ) >= Greater than or equal to
do this ; == Equal to
and this ; ~= Not equal to
end

(3) if ( condition ) Logical Operators


do this ; && Logical AND
else || Logical OR
do this ; & Logical AND for arrays
end | Logical OR for arrays
~ Logical NOT
(4) if ( condition )
do this ; The ‘disp’ Command:
and this ;
disp(name of a variable) or disp('text as string')
else
do this ; ex: x=2; y=3; z=x+y; disp(z).
and this ;
end ex:disp(‘my name is rajesh’)

(5) if ( condition ) disp(‘ ‘) display empty line


do this ;
else
if ( condition ) The fprintf Command:
do this ; fprintf ('text typed in as a string')
else
do this ; ex:fprintf(‘my name is rajesh’)
and this ; ex:fprintf(‘my name is rajesh.\n Iam fan of PSPK’)
end
end my name is rajesh.
Iam fan of PSPK
(6) if ( condition ) fprintf(' .. text ... %g ... %g ... %f ... ,variablel,variable2,variable3)
if ( condition )
do this ;
else
do this ;
and this ;
end
else
do this ;
end

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 49


MATLAB Elementary course

Exercise(if-else)

%comparing any three numbers,


print biggest number.
a=input('give first number');
b=input('give second number');
c=input('give third number');
if(a<b)
if(b<c)
disp(c)
else
disp(b)
end
else
disp(a)
end

1. Write program, which reads three numbers and prints the biggest.
2. Write program, which reads four numbers and prints the biggest.
3. Write program, which reads 2 numbers and prints both of them. The bigger number is
Print first.
4. Write program, which reads a, b and c as sides of a triangle and prints whether angle A is
90o(or) not. [Hint: if (a2 = = b2+c2) ] [Do not use cos-1 etc..]
5. Write program, which reads a, b, and c. Let ax + by + c = 0 be equation of a line. Print its slope.
The program also prints whether the line is vertical or not.
6. Write program, which reads a, b and c. Let ax2+ bx + c = 0 be a quadratic equation. If roots are
real and distinct then both roots are printed. If roots are equal then only one root is printed.
If roots are imaginary then real part and complex parts of both roots are printed. e.g. if input is
a=1 b=8 c=25 then output is –4, 3 and –3. if input a=2 b=8 c=8 output 2. Input 2 10 12 output -3
and -2.
7. Modify above program to print roots. e.g. for above input output -4+3i and -4-3i.
8. Write program, which reads three numbers. Two of these are same and one of them is different.
The program outputs the different number. e.g. input 5 5 2 output 2. Input 4 3 4 output 3. Input
5 2 2 output 5.
9. Write program, which reads 5 numbers a, b, c, d, and x. Here a, b, c, and d are distinct and x is
equal to exactly one of a or b or c or d. The program output which is equal to x.
e.g. input 5 7 9 6 7 output x is equal to b. input 8 7 1 3 1 output x is equal to c.
10. Write program, which reads 5 numbers a, b, c, d, and x. The program output how many
among a, b, c and d are equal to x. e.g. input 5 7 9 7 7 output 2. input 5 3 8 7 2 output 0.
input 5 2 2 2 5 output 1.
11. Write program, which reads three numbers. The program outputs the middle of these.
e.g. input 5 2 4 output 4. Input 5 6 2 output 5.
12. Read p, q, r, a, b, c. Let ax+by+c=0 be a line. Let (p,q) be the center of a circle and r be its
radius. The program finds whether the circle and the line intersect or not. If they intersect let A
and B be the points of intersection of the circle and the line. Find the area of the triangle
formed by A, B and the center of the circle. [Hint: Find the distance of the line from the center.
If it is more than the radius then circle and the line do not intersect. Otherwise find find the
chord length AB]. Input 5 4 10 1 1 20 output “no intersection”. Input 7 4 13 3 4 23 output 60.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 50


MATLAB Elementary course

a
2) a b 3)
a b

fix(a/10)
a*b a^3+b^2

5) 6)
a a a

b=rem(a,100)
fix(a/100)
b=rem(a,10) c=fix(a/10)

c=rem(b,10) d=fix(b,10)

d=rem(c,10)

e=c+d

8) a 9)
a
a

b=fix(a/10) c=rem(a,10) b=fix(a/10) c=rem(a,10)

b=fix(a,100)
c=rem(a,100)

d=c+c d=fix(b,10)

e=(b*10)+d d=fix(c,10) e=rem(c,10)

e=(d*10)+c

f=(e*10)+d

g=(b*100)+f

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 51


MATLAB Elementary course

Number Theory

1)Write a program which reads a number, prints whether is prime or not.


2)Write a program which reads a number ,prints whether is power of prime or not .
3)Write a program which reads a number ,prints whether is square free or not.
4)Write a program which reads a number ,prints number of divisors and sum of divisors .
5)Write a program which reads a number ,prints whether is perfect number or not.
6)write a program which read two number ,prints whether they are relative primes or not.
7)Write a program which reads a number ,prints whether is triangular number or not.
8)Write a program which reads a number ,prints whether is square number or not.
9)write a program which reads two numbers ,prints all prime number between two of them .
10)Write a program which reads a number ,prints all relative primes to the number.
11)Write program for Euler function.(write program which reads a number ,prints number of
relative primes to the number.)
12)Write a program which reads a, b two numbers ,prints last digit of ab.
(Ex: the last of (8099514167)8099514167 is
13)Write a program which reads a, b two numbers ,prints number of digits of the number ab.
14)Write a program to check the theorem “ Let p1, p2, p3,... .. pn are primes ,show that
p1*p2*p3*....*pn+1 divisible by None these primes.’’
15)Write a program to check the Fermat’s Theorem.(“If p is prime and (a,p)=1 then ap-11(modp’’).
16)Write a program to chech the Willson’s theorem.(“If p is prime then (p-1)!+10(modp”) .
17)Write a program which reads ‘n’ numbers a1,a2, a3,………….,an,print their G.C.D.
(ex:gcd(12,14,18,100)=2)
18) Write a program which reads ‘n’ numbers a1,a2, a3,………….,an,print their L.C.M.
(ex:lcm(12,14,18,100)=2)
19)Using 17,18
verify the theorem “gcd(a1,a2,a3,……..,an)*lcm[a1, a2, a3…………….,an]=a1*a2*……….*an’’.
20)Write a program which reads ‘n’ numbers a1,a2, a3,………….,an,print their mutual gcd.
i.e gcd(ai ,aj) for all i ,j.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 52


MATLAB Elementary course

Worksheet

1. Write a program, which prints all even numbers between 20 and 70.
2. Write program, which prints all numbers between 20 and 40, and all even numbers between
50 and 80.
3. Write program, which will print all even numbers less than 50 and all odd numbers more than
50.
4. Write program, which prints all even numbers between 20 and 40, and all odd numbers
between 50 and 80.
5. Write program, which will print all numbers which are multiple of either 3 or 7.
6. Write program, which will print all numbers which are either between 50 and 70, or less than
20, or more than 90.
7. Write program, which will print all numbers, which are even but not a multiple of either 3 or 5.
e.g. 2 4 8 14 16 22 ….
8. Write program, which will print all numbers, which are either a multiple of 3 or 5 but not both.
9. Write program, which will print those numbers whose last digit is multiple of 3.
e.g. 0, 3, 6, 9, 10, 13, 16, 19, 20, 23, …..
10. Write program, which will print those numbers whose last digit is between 5 and 8.
e.g. 5, 6, 7, 8, 15, 16, 17, 18, 25, 26, ….
11. Write program, which will print those numbers whose sum of both digits is multiple of 7.
e.g. 0,7,16, 25, 34, 43, 52, 59, 61, …..
12. Write program, which will print all numbers between 10 and 19, 30 and 39, 50 and 59, … , 90
and 99.
13. Write program, which will print those numbers whose first digit leaves remainder 1 when
divided by 3. e.g. 10, 11, ..., 19,40, 41, …, 49, 70, 71, ..., 79.
14. Write program, which will print all odd numbers between 0 and 9, 20 and 29, 40 and 49, … ,
80 and 89 and all even numbers between 10 and 19, 30 and 39, … , 90 and 99 .

15. Write program, which will print all odd numbers between 0 and 9, 20 and 29, 40
and 49, … , 80 and 89 and all even numbers between 10 and 19, 30 and 39, … , 90 and 99.
[Hint: check condition ((x/10)%2) != (x%2)].
16. Write program, which will print all even numbers between 10 and 29, 40 and 59, 70 and 89.
17. Write program, which will print all odd numbers between 0 and 9, 30 and 39, 60 and 69, 90
and 99 and all even numbers between 10 and 29, 40 and 59, 70 and 89.
18. Write program, which will print those numbers between 10 and 99, which after exchange of
digits become divisible by 7. e.g. 12, 19, 24, 36, 41, 48, 53, 65, 70, 77, 82, 89, 94.

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 53


MATLAB Elementary course

for i=1:10 #include<stdio.h>


for j=1:20 main()
if
((j+i<6)||((j>10)&&(i<8)))
{
a(i,j)='*'; int x,y;
else for (y=0;y<10;y++)
a(i,j)='O' {
end for (x=0;x<20;x++)
end if ((x+y<6) || ((x>10) && (y<8)))
end
a
printf("*");
else
printf("O");
MATLAB program printf("\n");
}
}

C programing

MATLAB Elementary course: By-Rajesh-Bandari-Yadav | +91-9700201340 54

S-ar putea să vă placă și