0% found this document useful (0 votes)
27 views50 pages

Matlab 02

Uploaded by

Md Rony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views50 pages

Matlab 02

Uploaded by

Md Rony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

# INTRODUCTION

What is MATLAB?

MATLAB is a software package for high performance numerical computation’s and visualization.
If provides an interactive environment with hundreds of built-in functions for technical
computation, graphics, and animation. Best of all, it also provides easy extensibility with its own
high -level programming language. The name MATLAB stands for MATrix LABoratory.

Application in mathematics?

MATLAB’s built –in functions provides excellent tools for linear algebra computations, data
analysis, signal processing, optimization, numerical solution of ordinary differential
equations(ODEs), quadrature, and many other types of scientific computations. There are
numerous functions for 2-D and 3-D graphics, as well as for animation. Also, for those who
cannot do without their Fortran or C codes.

1.3 BASICS OF MATLAB

MATLAB is normally operated from within the MATLAB integrated development environment (IDE).We
can launch MATLAB in the Windows environment by double-clicking
on the shortcut on our desktop, or by selecting it from the Start | Programs menu.

The IDE is organized into a header menu bar and several different windows. Which windows
are displayed can be determined by checking or unchecking items under the Layout menu
on the HOME tab. Some important windows for working with MATLAB are:

Command window: This is the main interactive interface to MATLAB. To issue a MATLAB
command, type the command at the >> prompt and press Enter on the keyboard.

Workspace browser: Each variable defined in the current workspace is represented here.
The name, class (type), value, and other properties of the variable can be shown. Choose
which properties to show using the View—Choose Columns menu from the header menu
bar. A recommended set to display is: Name, Value, and Class. Double-clicking on a
variable brings up the Variable Editor window. The icon representing numbers is meant
to symbolize an array, i.e., a vector or matrix. MATLAB’s basic data type is the array—
a number is treated as a 1×1 array.

Current Folder browser: In Windows parlance, the current folder is the same as the current
directory. Without further instruction, MATLAB will save files in the current folder and
look for files in the current directory. The browser displays files and other directories
(folders) that reside in the current directory. Icons at the top of the browser allow the
user to move up a directory (folder) level or to create a new folder. Double-clicking on a
displayed folder makes it the current folder.
Page 2 of 50
Editor window: The MATLAB editor is where programs are written. Launch the Editor
window by typing “edit” in the Command window and pressing Enter. It doubles as
part of the debugger interface, which is covered in detail later. The editor “knows” the
MATLAB language and color codes language elements. There are many other convenient
features to aid code-writing.

Figures window: Graphics is one of the main tools for visualizing numerical quantities.
The results of executing graphics-related commands, such as those for plotting lines and
surfaces, are displayed in the Figures window.

Variable Editor: The value or values held in a particular variable are displayed in a
spreadsheet-like tool. This is particularly useful for arrays (matrices and vectors)..

M-files:M-files are standard ASCII text files,with a(.m) extension to the file name. Any progrom written
in a MATLAB editor is saved as M-files .These files are futher classified as

*Script files

*Function files

SCRIPT FILES-An M-file with a set of valid MATLAB commands is called a script file. To run a script file,
the filename (without the .m extension) is entered in the Command Window, just as any other MATLAB
command

FUNCTION FILES- An M-file which begins with a function definition line is called a function file.

1.4 GENERAL COMMAND YOU SHOULD REMEMREB

help - list topics on which help available

help topic-provides help on topic

clear- clears the workspace, all variables are removed

clc- clears command window, command history is lost

clf- clears figure window

quit- quit MATHLAB

exit- same as quit

2. TUTORIAL LESSONS

2.1 A Minimum MATLAB Session

Goal:To learn to log on, invoke MATLAB, do a few trivial calculation, quit MATLAB, and log off.

Page 3 of 50
What you are going to learn

-How to do simple arithmetic calculation.The arithmetic operators are

Standard numerical operations are denoted by the usual symbols, and a very large number of functions
are available. Some examples follow.

+ addition
- subtraction
* multiplication
/ division
ˆ exponentiation, e.g., 1.3ˆ3.2 is 1.33.2
sin(x) returns the sine of x
sind(x) returns the sine of x degrees
cos(x) returns the cosine of x
cosd(x) returns the cosine of x degrees
tan(x) returns the tangent of x
tand(x) returns the tangent of x degrees
atan(x) returns the inverse tangent of x
atand(x) returns the inverse tangent of x in degrees
acos(x) returns the inverse cosine of x
acosd(x) returns the inverse cosine of x in degrees
asin(x) returns the inverse sine of x
asind(x) returns the inverse sind of x in degrees
exp(x) returns ex
log(x) returns the natural logarithm of x
log10(x) returns the log10(x)
sqrt(x) returns the square root of x
abs(x) returns the absolute value of x
round(x) returns the integer closest to x
ceil(x) returns the smallest integer greater than or equal to x
floor(x) returns the largest integer less than or equal to x
isprime(n) returns true if n is prime
factor(k) returns prime factors of k
sign(x) returns the sign (1 or −1) of x; sign(0) is 0
rand returns a pseudorandom number between 0 and 1
rand(m) returns an m×m array of random numbers
rand(m,n) returns an m×n array of random numbers

-How to assign values to variables.

-How to suppress screen output.

-How to control the appearance of floating point numbers on the screen.

-How to quit MATLAB.

Page 4 of 50
How to write in MATLAB?

Normal Operations MATLAB Command


Π pi
sqrt(x)
ex exp(x)
lnx/logex log(x)
Logx/log10x log10(x)
xn x^n
+ +
_ _
× *
÷ /
Sine sin
Cosine cos
Tangent tan
co-tangent cot
Cosecant cse
sin-1 asin
cos-1 acos
sin2x sin(x)^2
sinh2x sinh(x)^2
a+bi a+b*i
sint2 Sin(t)^2

# Tutorial lessons

Lesson -1: A Minimum MATLAB Session

Goal: To learn how to open MATLAB, do a few calculation’s, quit MATLAB

What we are going to learn

*How to assign value to variables.

*How to do simple arithmetic calculations.

*How to suppress screan output.

*How to quit MATLAB.

Simple arithmetic calculations by MATLAB:

Page 5 of 50
Example: >> 2+3

ans =5

>> 4-2

ans =2

>>2*3

Ans=6

>>9/3

Ans=3

>>10+4-2

Ans=12

>>5*6/2

Ans=15

>> quit Quit MATLAB. You quit can also quit by

selecting Quit from the file menu on Mace and PCs.

EXERCISES:

Arithmetic operations: compute the following quantities:

and compare with (1- )

Solution:

>> 2^5/(2^5-1) and >> (1-1/2^5 )^(-1)

ans = 1.0323 ans = 1.0323

Page 6 of 50
Solution:

>> (3*(sqrt(5)-1)/(sqrt(5)+1)*2)-1

ans = 1.2918

Area=π -1

Solution:

>> r=pi^(1/3)-1;

>> A=pi*r^2

A = 0.6781

2. Exponential and logarithms: calculate the following quantities:

* ln(e3), log10( )
, and log10( ).

Solution:

>> exp(3)

ans =20.0855

>> log(exp(3))

ans =3

>> log10(exp(3))

ans =1.3029

>> log10(10^5)

ans =5

Solution:

>> EXP(PI*SQRT(163))
Page 7 of 50
ANS = 2.6254 E +017

*SOLVE 3X=17 FOR X AND CHECK THE RESULT. (T HE SOLUTION IS X = . YOU CAN VERIFY THE RESULT BY
DIRECT SUBSTITUTION .)

SOLUTION: X=LOG(17)/LOG (3)

ANS=2.5789

3. TRIGONOMETRY: CALCULATE THE FOLLOWING QUANTITIES :

*SIN , COSΠ AND TAN

SOLUTION:>> SIN (PI/6)

ANS=0.5000

>>COS(PI)

ANS=-1

>> TAN(PI/2)

ANS=1.663 E +16

>>SIN2 2

SOLUTION: (SIN (PI/6)^2+COS(PI/6)^2)

ANS=1

>>Y=COSH2X-SINH2X,WITH X =32Π

SOLUTION: X=32*PI; Y=(COSH(X))^2-(SINH (X))^2

ANS=0

4. COMPLEX NUMBERS:

* . CAN YOU CHECK THE RESULT BY HAND CALCULATION ?

SOLUTION: (1+3I)/(1-3I)

ANS=-0.8000+0.6000 I
Page 8 of 50
*EI CHECK THE EULEER ’S FORMULA E
IX
=COSX-ISINX BY COMPUTING THE RIGHT -HAND SIDE TOO. I.E COMPUTE
COS (Π/4)+ ISIN(Π/4).

SOLUTION: EXP(I*PI/4)

ANS=0.7071+0.7071 I

*EXECUTE THE COMMANDS EXP(PI/2*I) AND EXP(PI/2I). CAN YOU EXPLAIN THE DIFFERENCE BETWEEN THE
TWO RESULTS ?

SOLUTION: >>EXP(PI/2*I)

ANS=0.0000+1.0000 I

>>EXP(PI/2I)

ANS=0.0000-1.0000 I

NOTE THAT
I
EXP(PI/2*I)=E =COS( )+ISIN ( )=I

EXP(PI/2I)=E =E- I =COS( )-ISIN( )=-I

Lesson 2

Creating and working with Arrays of numbers

Array: Array is a list of numbers or expressions arranged in horizontal rows and vertical
columns. when an array has only one raw or column, it is called a vector. An array with m rows
and n columns is called a matrix of size m × n.

Goal: To learn how to create arrays and vectors and how to perform arithmetic and
trigonometric operations on them.

What we are going to learn:

*How to create row and column vectors.

*How to create a vector of n numbers linearly(equally) spaced between two given numbers a
and b.

*How to do simple arithmetic operations on vectors.


Page 9 of 50
*How to do array operations:

.* term-by –terrm multiplication,

./ term-by-term division, and

.^ term-by-term exponentiation.

*How to use trigonometric functions with array arguments.

*How to use elementary math functions such as square root, exponentials, and logarithms with
array arguments.

*create a row vector with 3 elements.

>> x=[1 2 3]

x =1 2 3

*create a column vector with 3 elements:

>> y=[2;1;5]

y=

>> z =[2 1 0]; you can add (or subtract) a row vector to a column vector.

>> a=x+z

a=

3 3 3

>> b=x+y But you cannot add(or substract) a row vector to acolumn

Vector.

??? Error using ==> plus

Matrix dimensions must agree.

Page 10 of 50
>> a=x.*z you can multiply (or divide) the elements of two same-sized
vectors term by term with the array operator .*(./)

a=

2 2 0

>> b=2*a But multiply a vector with a scalar does not need any special operation (no dot
before the *)

b=

4 4 0

>> x=linspace(0,10,5) create a vector x with five elements linearly spaced between 0 and 10.

x=

Columns 1 through 3

0 2.5000 5.0000

Columns 4 through 5

>> y=sin(x); Trigonometric functions sin, cos, etc. as well as elementary math functions sqrt ,
exp, log, etc. operate on vectors term by term.

>> z=sqrt(x).*y

z=

Columns 1 through 3

0 0.9463 -2.1442

Columns 4 through 5

2.5688 -1.72037.5000 10.0000

EXERCISES:

Page 11 of 50
1. Equation of a straight line: The equation of a straight line is y=mx+c , where m and c are
constants. Compute the y-coordinates of a line with slope m=o.5 and the intercept c=-2 at the
following x-coordinates.
x=0, 1.5, 3, 4, 5, 7, 9, and 10

solution:
>> x=[0 1.5 3 4 5 7 9 10];
>> y=0.5*x-2

y=
-2.0000 -1.2500 -0.5000 0 0.5000 1.5000 2.5000 3.0000

2.Multiply, divide, and exponentiate vectors:create a vector t with 10 elements:1,2,3,. . . . .


10.Now compute the following quantities:
*x=tsin(t)
*y=

*z=
Solution:
>> t=1:10;
>> x=t.*sin(t);
>> y=(t-1)/(t+1);
>> z=sin(t.^2)./(t.^2);
3.Points on a circle : All points with coordinates x=cosθ and y=sinθ, where r is a constant, lie on
a circle with radius r,i.e, they satisfy the equation x2+y2=r2. Create a column vector for θ with
the values 0, , , , π, .Take r=2 and compute the column vectors x and y . Now check that x
and y indeed satisfy the equation of a circle , by computing the radius r=√(x 2+y2).
Solution:
>> theta=[0;pi/4;pi/2;3*pi/2;pi;5*pi/4];
>> r=2;
>> x=r*cos(theta);
>> y=r*sin(theta);
>> r=sqrt(x.^2+y.^2)
r=
2
2
2
2
Page 12 of 50
2
2
4. Geometric series:
The sum of a geometric series 1+r+r2+r3+……..+rn approaches the limit for r<1as n α
a. Create a vector n of 11 elements from 0 to 10.
b. Take r=.5 and create another vector x=[r0 ,r 1, r2…rn].
c. Now take the sum of vector with the command s=sum(x).
d. Calculate the limit and compare the compute sum s.
Solution:
>> n=linspace(0,10,11);
>> r=.5;
>> x=r.^n;
>> s=sum(x)
s = 1.9990
>> p=1/(1-r)
p= 2
a) Repeat the procedure taking n from 0 to 50 and then from 0 to 100.
>> n=linspace(0,50,11);
>> x=r.^n;
>> =sum(x)
=2.0000
>>n=linspace(0,100,11);
>>x=r.^n;
>> =sum(x)
=2.00

Creating and Printing Simple Plots


Goal: to learn how to make a simple 2-D plot in MATLAB and print it out.
What are going to learn :
*how to generate x and y co-ordinate of n equidistant points on unit circle.
*How to plot x vs. y and thus create the circle.
*How to set the scale of the x axis and the y axis to be the same, so that the circle looks like a
circle and not an ellipse.
*How to label the axes with text strings.
*How to title the graph with a text string.
*How to get a hard copy of the graph.

Page 13 of 50
The MATLAB commands used are:
Plot creates a line plot,
axis changes the aspects ratio of the x axis and y axis,
xlabel annotates the x axis ,
ylabel annotates the y axis,
title puts a title on the plot, and
print prints a hard copy on the plot.

*You are requested to draws a circle of unit radious by using the parametric equations of a unit
circle.
X=r cos , y=r sin θ, 0 circle of unit radious

Solution: 0.8

>> theta=linspace(0,2*pi,100); 0.6

>>x=cos(theta) 0.4
>>y=sin(theta);
0.2
plot(x,y)
>>xlabel('x') 0
y

>>ylabel('y') -0.2
>>axis(‘equal’) -0.4
>>title('circle of unit radious')
-0.6

-0.8

Figure: Circle of unit radius


-1 -0.5 0 0.5 1
EXERCISES: x
1. A simple sine plot: Plot y=sin(x), 0 ,taking 100 linearly spaced points in the given
interval.Lalel the axes and put " Plot created by Antor" in the title.
Command: plot created by Razik
>> x=linspace(0,2*pi,100); 1

>> plot(x,sin(x)) 0.8

>> xlabel('x') 0.6

>> ylabel('sin(x)') 0.4

>> title('plot created by Razik') 0.2


sin(x)

-0.2

-0.4

-0.6
Page 14 of 50
-0.8

-1
0 1 2 3 4 5 6 7
x
Figure: A simple sin plot
2.Line –styles: Make the same plot as above, but rather than displaying the graph as a curve,
show the unconnected data points.To display the data points with small circle, use polt(x,y,’0’).
Now combine the two plots with the command plot (x,y,x,y,’0’) to show the line through the
data points as well as the distinct data points.
Command:
plot created by Razik
>> x=linspace(0,2*pi,100); 1

plot(x,sin(x),x,sin(x),'+') 0.8
xlabel('x') 0.6
ylabel('sin(x)') 0.4
title('plot created by Razik') 0.2
sin(x)

-0.2

-0.4

-0.6
Figure: A simple line style
-0.8

-1
3.An exponentially decaying sine plot: Plot y=
0 1 sinx, 20 π 3 , taking
4 10,
5 50, and
6 1007
x
points in the interval. plot created by Mithun
0.6
Command:
>> x=linspace(0,4*pi,10); 0.5

>>y=exp(-0.4*x).*sin(x)
0.4
>>plot(x,y)
>>xlabel('x') 0.3

>>ylabel('y') 0.2
y

title('plot created by Mithun')


0.1

-0.1
Figure: An exponentially decaying sine plot
-0.2
0 2 4 6 8 10 12 14
x

>> x=linspace(0,4*pi,50); plot created by Mithun


0.6
y=exp(-0.4*x).*sin(x)
plot(x,y) 0.5
xlabel('x')
0.4
Page 15 of 50
0.3

0.2
y
ylabel('y')
title('plot created by Mithun')

Figure:An exponentially decaying sine plot


4.space curve: Use the command plot3(x,y,z) to plot the circular helix x(t)=sint, y(t)=cos(t),
z(t)=t, 0
Command:
>>t=linspace(0,20,100);
>>plot3(sin(t),cos(t),t) 25

20
,
15

10

0
1
0.5 1
0 0.5
0
-0.5
Figure:Space curve -0.5
-1 -1

5.Overlay plots: Plot y=cosx, and z=1- + for 0 on the same plot.You might like to
read to learn how to plot multiple curves on the same graph.
Command:
plot created by Antor
>> x=linspace(0,pi,100); 25

>>y=cos(x);
>>z=1-x.^2/2+x.^4/4; 20

>>plot(x,y,x,z)
>>plot(x,y,x,z,'+') 15

>>Xlabel('X')
>>Ylabel('Y') 10
Y

>>title('plot created by Antor')


5

Page 16 of 50
0

-5
0 0.5 1 1.5 2 2.5 3 3.5
X
Figure: Overlay plots

6.Show the center of the circle: Modify the script file circle. m to show the center of the circle
on the plot, too. Show the center point with a "+".

Command : theta=linspace(0,2*pi,100) 1

x=cos(theta) 0.8
y=sin(theta) 0.6
plot(x,y,0,0,'+') 0.4
xlabel('X') 0.2
ylabel('Y')
0

Y
axis('qual')
-0.2
title('Plot created by RAZIK')
-0.4

-0.6

-0.8
Figure : Unit circle
-1
with the center point “+”
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
X

7.Variable in workspace: All variables created by a script file are left in the global workspace.
You can get information about them and access them, too.
*Type who to see the variables present in your workspace. You should see the variables r,
theta, x, and y in the list.
*Type whos to get more information about the variables and the workspace.
*Type *theta’ x’ y’+ to see the values of θ, x and y listed as three columns. All three variables are
row vectors. Typing a single right quote (‘) after their names transpose them and makes them
column vectors.
8. write a matlab command to convent the temperature from celsious to farenhiet
F= c+32
Command:
>> c=45;
>> f=(9/5)*c+32
Ans=
f=
113

9.Write a MATLAB command to compute the factorial of any integer


Page 17 of 50
Prod(1:n)
Matlab command:
>> n=10;
>> prod(1:n)
ans =3628800

10.write a MATLAB command to find the interest on 1000 at the rate of 6% a year at the end of
5 years if the interest is compound
a. annually
command:
>> p=1000;
>> n=5;
>> i=.06;
>> t=1;
>> A=p*(1+i/t)^t*n
A =5300

# Matrices and Vectors

# Input: A matrix is entered row-wise,with consecutive elements of a row separated by a


space or comma,and the rows separated by semicolons or carriage returns. The entire matrix
must be enclosed within square brackets . Elements of the matrix may be real
numbers,complex numbers or valid MATLAB expressions.
Problem: Write MATLAB input command for the following matrices:-

I. A=( )

Command: A = [1 2 5;3 9 0]

II. B=( )

Command: B = [2*x log(x)+sin(y);5*i 3+2*i]

III. C=( )

Command: C=[1 3;5 10;4 2]

Page 18 of 50
IV. D=( )

# Indexing(or subscripting)
I. A(i,j)=refers to the element of of matrix A,i.e.,the element in the ith row and jth column.

Example: A(2,3)=

II. A(m:n,k:l)=specifies rows m to n and columns k to l of matrix A.

Example:A(2:5,3:6)=refers to the elements in rows 2 through 5 and in columns 3 through 6 of


matrix A.

III. A( : ,k:l)=specifies columns k to l of all rows of matrix A.

Example:A( : ,3:6)=refers to the elements in columns 3 through 6 of all rows of matrix A.

A(m:n, : )=specifies rows m to n of all columns of matrix A.

Example:A(2:5, : )=refers to the elements in rows 2 through 5 of all columns of matrix A.

# Dimension

Matrix dimensions are determined automatically by MATLAB, i.e., no explicit dimension


declarations are required.The dimensions of an existing matrix A may be obtained with the
command size(A) or more explicitely with [m,n]=size(A),which assigns the number of rows and
columns of A to the variables m and n, respectively.

B(2,3)=5

C(3,1:3)=[1 2 3]

Problem : Enter the matrix A=( ) then

a) Find and
b) Replace by
c) Create a submatrix of a taking rows from 2 to 3 and columns from 1to 3
d) Obtain a submatrix of A taking rows from 2 to 3 and all columns.

Command

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

Page 19 of 50
b) A(2,3)

A(3,1)

c) A(3,3)=9
d) A(2:3,1:3)
e) A(2:3,:)

# Appending a row or column


can be easily append to an existing matrix, provided the row has the A row same length as the
length of the row has the existing matrix. The same thing goes for columns. The command
A=[A v] appends the column vector u to the column of A, while A=[A;u] appends the row vector
v to the rows of A. A row or column of any size may be appended to a null matrix.
Examples

If A=[ ], u=[ ], and v=[ ] then

A=[A; u] produces A=[ ]

A=[A v] produces A=[ ]

A=*A u’+ produces A=[ ]

A =[A u] produces An error.

B=[ ]; B=[B; 1 2 3] produces B=[ ]

Deleting a row or column

Any row or column of a matrix can be deleted by setting the row or column to a null vector.

*A(2, :) = [ ] deletes the 2nd row of matrix A,

*A(: ,3:5) = [ ] deletes the 3rd through 5th columns of A,

*A([1 3], :)=[ ] deletes the 1st and the 3rd row of A, and

*u(5:length(u))= [ ] deletes all elements of vector u except 1 through 4.

Page 20 of 50
# Reshaping matrices

Matrices can be reshaped into a vector or any other appropriately sized matrix;

As a vector: All the elements of matrix A can be strung into a single-column vector b by the
command b=A(:) (matrix A is stacked in vector b columnwise).

As differently sized matrix: If matrix A is an m×n matrix, it can be reshaped into a p×q matrix,
as long as m×n=p×q,with the command reshape (A,p,q).Thus,for a 6×6 matrix A,

reshape(A,9,4) transforms A into a 9×4 matrix

reshape(A,3,12) transforms A into a3×12 matrix

Transpose

The transpose of matrix A is obtained by typing A’, i.e., the name of the matrix followed by the
single right quote. For a real matrix A, the command B=A’ produces B=A T and for a complex
matrix A, B=A’ produces the conjugate transpose B=AT.

Examples:

If A=* + then B=A’ gives B=* +

If C=* + then Ct=C’ gives Ct=* +.

Utility matrices

To aid matrix generation and manipulation, MATLAB provides many useful utility matrices.For
example,

eye(m,n)=returns an m by n matrix with ones on the main diagonal.

Zeros(m,n)=returns an m by n matrix of zeros

Ones(m,n)=returns an m by n matrix of ones.

rand(m,n)=returns an m by n matrix of random numbers.


Page 21 of 50
diag(v)=generates a diagonal matrix with vector v on the diagonal.

diag(A)=extracts the diagonal of matrix A as a vector tri1=extracts the lower


triangular part of matrix.

triu=extracts the upper triangular part of a matrix.

# Matrix and Array operations

#Arithemetic operations

+ addition
- subtraction
* multiplication
/ division
^(caret) exponentiation
A+B is valid if A and B are of the same size.

A-B is valid if A and B are of the same size.

A*B is valid if A’s number of columns equal and B’s number of rows.

A/B is valid and equals A.B-1 for same-size square matrices.

A^2 which equals A*A, makes sense only if A is square.

A+α(α scaler)=adds α to each element of A.

A*α(α*A)=multiplies each element of A .

Note: What will be happened if you use A*B, A.^2 etc in above.

#Array operation

.* Element by element multiplication


./ Element by element left division
.\ Element by element right division
.^ Element by element exponensiation
.’ Nonconjugated transpose

Examples:If u and v are two vectors then

u.*v produces element by element multiplication.

Page 22 of 50
u./v produces element by element division.

u.^v produces element by element exponentiation.

Matrix functions

exp(A)= produce a matrix with elements e( )

log(A)=produce a matrix with elements ln( )

log10(A)=produce a matrix with elements log10( )

sqrt(A)=produce a matrix with elements of

expm(A) = finds eA

logm(A) =finds elog(A)

sqrtm(A) =finds A

det(A)= finds determinate of A

inv(A) =finds A-1

eig(A)= finds eigenvalues of A in a column vector

[eigvec,eigval]=eig(A) finds eigenvectors of A in the matrix eivec and the eigen values of on
the diagonal of the matrix eigval.

#Linear Algebra

# Solve the system of linear equation .

1. Solve : 5x-3y+2z=10
-3x+8y+4z=20
2x+4y-9z=9

Ax=b, where A=( ) ; x=( ) ; b=( )

Command: >> A=[5 -3 2;-3 8 4;2 4 -9];

>> b=[10 20 9];

Page 23 of 50
>> x=A\b

2.Do the same using the inverse of the co-efficient matrix

Ax=b

Or, x=A-1b

Command: >> x=inv(A)*b

3.Do the same using ‘Cremers rule

Command: >> x=det( )/det(A)

>> y=det( )/det(A)

>> z=det( )/det(A)

# Gaussian elimination:

Introductory linear algebra courses, we learn to solve a system of linear algebraic equations
eliminations. This technique requires forming a rectangular matrix that contains both the
coefficient matrix A and the known vector b in an augmented matrix. Gauss-Jordan reduction
procedure is then used to transform the augmented matrix to the so-called row reduced
echelon form. MATLAB has a built in function, rref, that does precisely this reduction,
transforms the matrix to its row reduced echelon form Ax=b

*Solve the following system of linear equation by Gauss-jordon method.

5x-3y+2z=10

-3x+8y+4z=20

2x+3y-9z=9

Command:

>> a=[5 -3 2;-3 8 4;2 3 -9];

>> b=[10;20;9];

>> c=[a b];


Page 24 of 50
>> cr=rref(c)

cr =

1.0000 0 0 3.6610

0 1.0000 0 3.3995

0 0 1.0000 0.9467

The last column of cr is the solution of x.

*IF A=( )and f(x) =2x3-4x+5 then find f(x)

Command:

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

>> f(A)=2*A^3-4*A+5*eye(2)

f=

83 76 159 152

*If A=( ) then write down the command to find the eigenvalues and eigenvectors of

A. Also verify the cay-ley Hamilton theorem.

f(x)=x3-11x2+39x-45 find f(A)

command:

>> [V,D]=eig(A)

V=

-0.7071 -0.4472

Page 25 of 50
0.7071 -0.8944

D=

-1 0

0 5

>> p=poly(A)

p=

1 -4 -5

>> f(A)=A^3-11*A^2+39*A-45*eye(2)

f=

-64 32 -32 64

*Enter the following matrix three matrix,

A=( ) ,B=( ) and c=( )

1. compute A+B and B +A ,also compare the results.


2. Compute (A +B)+C, A +(B+C)
3. For 5, compute A(B+C) and αA+αB
4. compute A(B+C) and AB+AC

Command:

>> A=[2 6;3 9];

>> B=[1 2;3 9];

>> C=[-5 5;5 3];

1.>> x=A+B

x=

3 8

6 18
Page 26 of 50
>> y=B+A

y=

3 8

6 18

2.>> p=(A+B)+C

p=

-2 13

11 21

>> q=A+(B+C)

q=

-2 13

11 21

3.>> alpha=5;

>> r=A*(B+C)

r=

40 86

60 129

>> t=alpha*A+alpha*B

t=

15 40

30 90

4.

>> v=A*(B+C)

v=

Page 27 of 50
40 86

60 129

>> m=A*B+A*C

m=

40 86

60 129

*Create the following matrixes with the help of matrix generation functions, zeros, eye, and

ones , D=* + , E =[ ] , F=* +

Command:

>> D=zeros(2,3)

>> E=eye(3)*5

>> F=ones(2)*3

*Create a 10 random matrix G.

Then

1. Delete the last row and last column of the matrix


2. Extract the first 4×4 submatrix from G
3. Replace G(5,5) with 4
4. What do you get if you type G(1,3) and hit return?
5. What happen if you are type G(12,1)=1 and hit return?

Command:

>> G=rand(10*10);

1.>> G(10,:)=[];

Page 28 of 50
2.>> G(:,10)=[];

3.>> G(1:4,1:4)=4

4. >> G(13);

If I type G(13) and hit return then I get the element of rows ‘3’ and columns ‘2’

6. >> G(12,1)=1;

If I type G(12,1)=1 and hit return then the elements of rows 12 and columns 1is replaced
by 1 and the other element of extra rows 11 ,12 is filled by 0.

Graphics

Basic 2-D plot

Plot (x,y) plots y vs x with a solid line

Plot (x,y,’--’) plots y vs x with a dashed line

Plot (x) plots y vs x with the elements of x against their row index .

Style option:-The style option in the plot command in a character string that consists of
1,2,or character that specify the color and /or the line style. There are several color link
and marked style option.

Color line option Line style option Marker style option

y yellow - Solid + plus sign


m magenta --dashed 0 circle
C cyan : dotted * asterisk
R red -. dash dot X x mark
G green . point
B blue ^ uptriangle
W white S square
K black D diamond

The style option is made up of either the color option, the line style option or a
combination of the two.

*example:
Page 29 of 50
Plot(x,y,’r’) plot y vs x with a red solid line

Plot(x,y,’b--’) plot y vs x with a blue dashed line

Plot(x,y,’:’) plot y vs x with a dotted line

Plot(x,y,’+’) plots y vs x as unconnected point marked by +

*Labels, title, legend, and, other text objects

X label(‘pipe length’) label the x axis with pipe length .

Y label (‘fluid pressure’) label the y axis with fluid pressure.

Title(‘pressure variation’) titles the plot with pressure variation.

LEGEND: The legend command produced a boxed legend on a plot.

LEGEND OFF: deletes the legend from the plot

*Axis control :

axis ([-5 10 2 22]) sets the x axis from -5 to 10 and y axis 2 to 22

axis([-5 10 –inf 22]) sets the x axis from -5 to 10 and y axis limit to be set automatically

axis([-5 inf –inf 22]) sets the lower limit of x –axis and the upper limit of y-axis ,and leaves
the other two limits to be set automatically.

OVERLAY PLOTS

Method 1: Using the plot command to generate overlay plots.

# Plot y1=sint, y2=t , and y3 +

>> t=linspace(0,2*pi,100)

>>y1=sin(t)

>>y2=t;

>>y3=t-(t.^3)/6+(t.^5)/120

Page 30 of 50
>>plot(t,y1,t,y2,'--',t,y3,'+')

>>axis([0 5 -1 5])

>>xlabel('t')

>>ylabel('Approximination of sin(t)')

>>title('plot created by Antor')

>>text(3.5,0,'sin(t)')

>>gtext('linear approximination')

>>gtext('first 3 term')

>>gtext('is taylor series')

***Plot y1=sint;y2=t;y3=t- /6+

t=linspace(0,2*pi,100)
y1=sin(t);
y2=t;
y3=t-(t.^3)/6+(t.^5)/120
plot(t,y1,t,y2,'--',t,y3)
axis([0 5 -1 5])
xlabel('t')
ylabel('Approximination of sin(t)')
title('rajeeb')
text(3.5,0,'sin(t)')
legend('sin(t)','linear approx','fifth-order approx.')
gtext('linear approximination')
gtext('first 3 term')
gtext('is taylor series')

Page 31 of 50
rajeeb
5
sin(t)
linear approx
4 fifth-order approx.
Approximination of sin(t)

3 linear approximination

first 3 term

2
is taylor series

0 sin(t)

-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t

Using hold command:

x=linspace(0,2*pi,100);
y1=sin(x);
plot(x,y1);
hold on
y2=x;
plot(x,y2,'--')
y3=x-(x.^3)/6+(x.^5)/120
plot(x,y3,'+')
axis([0 +5 -1 5])
xlabel('x')
ylabel('Approximination of sin(x)')
title('rajeeb')
text(3.5,0,'sin(x)')
legend('sin(x)','linear approx','fifth-order approx.')
gtext('linear approximination')
gtext('first 3 term')
gtext('is taylor series')

Page 32 of 50
rajeeb
5
sin(x)
linear approx
4 fifth-order approx.

linear approximination
Approximination of sin(x)

3
first 3 term

2 is taylor series

0 sin(x)

-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
x

Using line command:

t=linspace(0,2*pi,100);
y1=sin(t);
y2=t;
y3=t-(t.^3)/6+(t.^5)/120;
plot(t,y1);
line(t,y2,'linestyle','--')
line(t,y3,'marker','+')
axis([0 5 -1 5])
xlabel('t')
ylabel('Approximination of sin(t)')
title('rajeeb')
text(3.5,0,'sin(t)')
legend('sin(t)','linear approx','fifth-order approx.')
gtext('linear approximination')
gtext('first 3 term')
gtext('is taylor series')

Page 33 of 50
rajeeb
5
sin(t)
linear approx
4 fifth-order approx.

linear approximination
Approximination of sin(t)

3 first 3 term

is taylor series
2

0 sin(t)

-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t

****f(x)=xsinx,0≤x≤10π

Function example script output

Page 34 of 50
Fplot fplot('x.*sin(x)',[0 10*pi])
30

20

10

-10

-20

-30
0 5 10 15 20 25 30

Semilogx X= ,y=t, 0≤t≤2π 7


t=linspace(0,2*pi,200);
x=exp(-t); 6

y=t;
5
semilogx(x,y),grid
4

0
-3 -2 -1 0
10 10 10 10

semilogy X=t,y= ,0≤t≤2π 10


3

t=linspace(0,2*pi,100);
semilogy(t,exp(t));
grid
2
10

1
10

0
10
0 1 2 3 4 5 6 7

Page 35 of 50
Loglog X= ,y=100+ ,0≤t≤2π 10
6

t=linspace(0,2*pi,200);
x=exp(t);
y=100+exp(2*t);
5
10

loglog(x,y),grid
4
10

3
10

2
10
0 1 2 3
10 10 10 10

Polar , 0≤t≤2π
t=linspace(0,2*pi,100); 90 1.5
120 60
r=sqrt(abs(2*sin(5*t)));
polar(t,r) 1

150 30
0.5

180 0

210 330

240 300
270

Page 36 of 50
Fill , 0≤t≤2π
1.5
x=rcost,y=rsint

t=linspace(0,2*pi,100); 1
r=sqrt(abs(2*sin(5*t)));
x=r.*cos(t); 0.5
y=r.*sin(t);
fill(x,y,'k'),
axis('square'); 0

-0.5

-1

-1.5
-1.5 -1 -0.5 0 0.5 1 1.5

Plot3 X(t)=t,y(t)= ,z(t)= , 0≤t≤1


t=linspace(0,1,100);
x=t;
1
y=t.^2;
z=t.^3; 0.8

plot3(x,y,z); 0.6
grid;
0.4
xlabel('X')
ylabel 0.2

0
1
1
0.8
0.5 0.6
0.4
0.2
0 0
X

Page 37 of 50
Surf √

Z=cosx cosy
,| | | |
u=-5:.2:5; 1
[X,Y]=meshgrid(u,u);
Z=cos(X).*cos(Y)...
0.5
exp(-sqrt(X.^2+Y.^2)/4);
surf(X,Y,Z)
0

-0.5
5
5
0
0

-5 -5

Surfc √

Z=cosx cosy
,| | | |

>> u=-5:.2:5;
[X,Y]=meshgrid(u,u);
Z=cos(X).*cos(Y).*exp(-
sqrt(X.^2+Y.^2)/4);
surfc(Z)
axis off
>>

Page 38 of 50
Mesh Z= ,| | | |
x=linspace(-3,3,50);
y=x; 0
[x,y]=meshgrid(x,y);
-1
z=-5./(1+x.^2+y.^2);
mesh(z) -2

-3

-4

-5
60
50
40
40
30
20 20
10
0 0

meshz Z= + y,
| |≤ | |
x=linspace(-3,3,50);
y=x;
[x,y]=meshgrid(x,y);
z=sin(x.^2)+sin(y.^2) 1

meshz(x,y,z),axis tight 0

view(-37.5,50) -1

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

Page 39 of 50
waterfall Z= ,| | | |

x=linspace(-3,3,50);
0
y=x;
[x,y]=meshgrid(x,y); -1

z=-5./(1+x.^2+y.^2);
-2
waterfall(z)
hidden off -3

-4

-5
60
50
40
40
30
20 20
10
0 0

comet Y=tsint,0
t=linspace(0,10*pi,2000); 25

y=t.*sin(t); 20

comet(t,y) 15

10

-5

-10

-15

-20

-25

0 5 10 15 20 25 30

Page 40 of 50
1.4

1.2

0.8

0.6

0.4

0.2

0
0 0.5 1 1.5 2 2.5 3

Figure: bar plot

Barh plot:
cont=char('Asia','Europe','Africa','America','s.America');
pop=[3332;696;694;437;307];
barh(pop)
for i=1:5,
gtext(cont(i,:));
end
Xlabel('population in millions')
title('World population (1992)','fontsize',18)

Page 41 of 50
World population (1992)
s.America
5

America
4

3 Africa

2 Europe

1 Asia

0 500 1000 1500 2000 2500 3000 3500


population in millions

Figure: barh plot

Pie plot: cont=char('Asia','Europe','Africa','America','s.America');


pop=[3332;696;694;437;307];
pie(pop)
for i=1:5,
gtext(cont(i,:));
end
Xlabel('population in millions')
title('World population (1992)','fontsize',18)

Page 42 of 50
World population (1992)
6%

8%

s.America
America

13%

Africa

Asia
Europe
61%
13%

Figure: pie plot

Differential Calculus:

Limit:

Mathematical operator MATLAB Command


Limit(f)
Limit(f,a)
Limit(f,x,a,’left’)
Limit(f,x,a,’right’)

Differentiate following case:

Page 43 of 50
1.Find | |

2.Test whether the limit of at x=0 exist or not

3.Find

4.A function ∫ is defined as follows:∫ ={ show that ∫ doesn’t

exist

5.A function f(x) is defined as follows:∫ { ,test whether limit of ∫ at x=0

and x=1 exist or not

Solution:

1. syms x
limit(x/abs(x),0)
ans =
NaN
l.h.l=limit(x/abs(x),x,0,'left')
l=
h: [1x1 struct]
r.h.l=limit(x/abs(x),x,0,'right')
r=
h: [1x1 struct

2. l.h.l=limit((x+cos(x))/x,x,inf,'left')
l=
h: [1x1 struct]
r.h.l=limit((x+cos(x))/x,x,inf,'right')
r=
h: [1x1 struct]
limit((x+cos(x))/x,inf)
ans =
1
l.h.l=limit(x^2),x,1,'left')

l.h.l=limit((x^2),x,1,'left')
Page 44 of 50
l=
h: [1x1 struct]

3. l.h.l=limit((x+cos(x))/x,x,inf,'left')
l=

h: [1x1 struct]

r.h.l=limit((x+cos(x))/x,x,inf,'right')
r=

h: [1x1 struct]

limit((x+cos(x))/x,inf)
ans =

4.4. l.h.l=limit(x^2,x,1,'left')
l=

h: [1x1 struct]

r.h.l=limit(x^2+2,x,1,'right')
r=

h: [1x1 struct]

5. l .h.l=limit((x^2+1),x,0,'left')

l=

h: [1x1 struct]

r .h.l=limit(x,x,0,'right')

r=

Page 45 of 50
h: [1x1 struct]

Maxima and Minima:


***Problem:Find maxima and minima of ∫ ;x€*0,4+
Solution:
>> syms x
f=x^4-4*x^3+2*x^2+4*x+2
1. f1=diff(f)
cp=solve(f1)
f2=diff(f,2)
x=1
f2

f=

x^4 - 4*x^3 + 2*x^2 + 4*x + 2

f1 =

4*x^3 - 12*x^2 + 4*x + 4

cp =

1
1 - 2^(1/2)
2^(1/2) + 1

f2 =

12*x^2 - 24*x + 4

x=

f2 =

Page 46 of 50
12*x^2 - 24*x + 4

INTREGATE

Indefinite Intregate

 compute the following case

a.∫ .

b. ∫ dx.

c .∫ dx.

d .∫

e .∫

Solution:

a .int(sin(x)*cos(x),x)

ans =

sin(x)^2/2

b .int((1-cos(2*x))/(1+cos(2*x)),x)

ans =

tan(x) – x

c .int(asin(x),x)

ans =

x*asin(x) + (1 - x^2)^(1/2)

d.int(1/((1+x^2)*atan(x)),x)

ans =

log(atan(x))

Page 47 of 50
e.int(1/(x^2+6*x+25),x)

ans =

atan(x/4 + 3/4)/4

Definite intregate

 Compute the following case

a.∫ dx .

b .∫ dx.

c .∫ dx.

d .∫ dx

e .∫

Solution:

aint(cos(2*x)*cos(3*x),x,0,pi/2)

ans =

3/5

b. int(sqrt(16-x^2),x,0,4)

ans =

4*pi

c. int(asin(x)/sqrt(1-x^2),x,0,1)

ans =

pi^2/8

Page 48 of 50
d .int(3*sqrt(1-cos(x))*sin(x),x,0,pi)

ans =

4*2^(1/2)

e. int(x/sqrt(4-x^2),x,0,1)

ans =

2 - 3^(1/2)

Differential Equation:
Write MATLB command to solve the following D.E.
1. =1+

dsolve('Dy=1+y^2')

ans =

i
-i
tan(C3 + t)

2. =1+ ,y(0)=1

>> y=dsolve('Dy=1+y^2','y(0)=1')

y=

tan(pi/4 + t)

3. +4y= ,y(0)=0,y’( )=0

>> dsolve('D2y+4*y=exp(-2*x)','y(0)=0','Dy(pi)=0','x')

ans =

Page 49 of 50
sin(2*x)/(8*exp(2*pi)) - cos(2*x)/8 - (sin(2*x)*(cos(2*x) - sin(2*x)))/(8*exp(2*x)) +
(cos(2*x)*(cos(2*x) + sin(2*x)))/(8*exp(2*x))

4.solve =- ;y(4)=3;

>> dsolve('Dy=-(x/y)','y(4)=3','x')

ans =

2^(1/2)*(25/2 - x^2/2)^(1/2)

***THE END***

Page 50 of 50

You might also like