6 views

Uploaded by Fahad Mahmood

DSP lab

- CXC 1993
- Matlab
- Propiedades Extremas de Valores Propios Tropicales
- L01.pdf
- ES440F90Lab1_24jan08
- Intro Matlab
- MAT FemIngles
- Linear Algebra Spring 2015
- Excel Functions
- Lab Manual
- Determinants
- Data Analysis
- Maths Ulangkaji
- CCPL 1C Pradeep
- Matlab Course
- Introduction to MATLAB
- Efecto Stark Lineal
- Code Pool
- Matlab Mini Manual
- business_maths_chapter_3.docx

You are on page 1of 16

Objectives:

To study basic plotting functions and to familiarize student with matrices, arrays their

operation loops and function file

Equipment / Tool:

Matlab

Background:

Plotting Elementary Functions:

Suppose we wish to plot a graph of y = sin3πx for 0 ≤ x ≤ 1. We do this by sampling the

function at a sufficiently large number of points and then joining up the points (x, y) by

straight lines. Suppose we take N+1 points equally spaced a distance h apart:

Defines the set of points x = 0, h, 2h . . . 9h, 1. The corresponding y values are computed by

>> y =sin(3*pi*t);

and finally, we can plot the points with

The result is shown in Figure 1, where it is clear that the value of N is too small.

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

>> N =100; h =1/N; t =0:h:1;

>> y =sin(3*pi*t); plot(t,y)

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

To put a title and label the axes, we use

>> xlabel (’t-axis (time)’)

>> ylabel (’y-axis’)

The strings enclosed in single quotes, can be anything of our choosing.

Grids:

A dotted grid may be added by

>> grid

This can be removed using either grid again, or grid off.

The default is to plot solid lines. A solid white line is produced by

The third argument is a string whose first character specifies the color (optional) and the

second the line style. The options for colors and styles are:

b blue . point

g green o circle

r red x x-mark

c cyan + plus

m magenta * star

y yellow s square

k black -. dashdot

Multi–plots

Several graphs can be drawn on the same figure as:

A descriptive legend may be included with

Which will give a list of line–styles, as they appeared in the plot command, followed by a

brief description. MATLAB fits the legend in a suitable position, so as not to conceal the

graphs whenever possible. For further information do help plot etc. The result of the

commands

>> grid

Multi-plot

1

0.8

0.6

0.4

0.2

y axis

-0.2

-0.4

-0.6

-0.8

-1

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

x axis

Hold

A call to plot clears the graphics window before plotting the current graph. This is not

convenient if we wish to add further graphics to the figure at some later stage. To stop the

window being cleared:

>> plot (t, y, ’gx’), hold off

“hold on” holds the current picture; “hold off” releases it (but does not clear the window,

which can be done with clf). “hold” on its own toggles the hold state.

Subplot

The graphics window may be split into an m × n array of smaller windows into which

we may plot one or more graphs. The windows are counted 1 to mn row–wise, starting

from the top left. Both hold and grid work on the current subplot.

>> xlabel (’x’), ylabel (’sin 3 pi t’)

>> subplot (222), plot (t, cos (3*pi*t))

>> xlabel (’x’), ylabel (’cos 3 pi t’)

>> subplot (223), plot (t, sin (6*pi*t))

>> xlabel (’x’), ylabel (’sin 6 pi t’)

>> subplot (224), plot (t, cos (6*pi*t))

>> xlabel (’x’), ylabel (’cos 6 pi t’)

subplot(221) (or subplot(2,2,1)) specifies that the window should be split into a 2 × 2 array

and we select the first sub-window.

1 1

0.5 0.5

cos 3 pi x

sin 3 pi x

0 0

-0.5 -0.5

-1 -1

0 0.5 1 0 0.5 1

x x

1 1

0.5 0.5

cos 6 pi x

sin 6 pi x

0 0

-0.5 -0.5

-1 -1

0 0.5 1 0 0.5 1

x x

Zooming

We often need to “zoom in” on some portion of a plot in order to see more detail. This is

easily achieved using the command

>> zoom

Left-Click on plot = Zoom in

Selecting a specific portion of the plot using the mouse will zoom in to the selected portion of

the plot

Controlling Axes

Once a plot has been created in the graphics window you may wish to change the range of x

and y values shown on the picture.

>> y =sin (3*pi*t); plot (t,y)

>> axis ([-0.5 1.5 -1.2 1.2]), grid

The axis command has four parameters, the first two are the minimum and maximum

values of x to use on the axis and the last two are the minimum and maximum values of y.

Note the square brackets. The result of these commands is shown in Figure 4. For more

info, check out help axis.

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1

Examples in Plotting

Example: Draw graphs of the functions

i. y = sin(x)/x

ii. u= (1/(x-1)2)+x

iii. v= (x2+1)/(x2-4)

iv. ((10-x)1/3-1)/(4 - x2)1/2

Solution:

>> x = 0:0.1:10;

>> y = sin(x)./x;

>> subplot (221), plot (x, y), title (’(i)’)

>> u = 1./(x-1).^2 + x;

>> subplot (222), plot (x, u), title(’(ii)’)

>> v = (x.^2+1)./(x.^2 -4);

>> subplot(223), plot(x, v), title(’(iii)’)

>> w = ((10-x).^(1/3)- 1)./sqrt(4-x.^2);

>> subplot (224), plot (x, w), title(’(iv)’)

Note the repeated use of the “dot” operators. Experiment with changing the axes, grids and

hold.

>> grid

>> grid

>> hold on

>> plot (x, v, ’--’), hold off, plot (x, y, ’:’)

We could do this by giving 8 separate plot commands but it is much easier to use a loop.

The simplest form would be

>> x =-1:0.05:1;

>> for n =1:8

subplot (4,2,n), plot (x, sin (n*pi*x))

end

For loop

All the commands between the lines starting “for” and “end” are repeated with n being

given the value 1 the first time through, 2 the second time, and so forth, until n = 8. The

subplot constructs a 4 × 2 array of sub-windows and, on the nth time through the loop, a

picture is drawn in the nth sub-window. The commands

>> x =-1:.05:1;

>> for n =1:2:8

subplot (4,2,n), plot (x, sin (n*pi*x))

subplot (4,2,n+1), plot (x, cos(n*pi*x))

end

Draw sin nπx and cos nπx for n = 1, 3, 5, 7 alongside each other. We may use any legal

variable name as the “loop counter” (n in the above examples) and it can be made to run

through all of the values in a given vector (1:8 and 1:2:8 in the examples). We may also use

for loops of the type

.......

end

which repeats the code as far as the end with counter=23 the first time, counter=11 the

second time, and so forth. (Keep in mind that using a for loop in MATLAB is very much

discouraged because they are computationally inefficient.)

About Matrices:

In the MATLAB environment, a matrix is a rectangular array of numbers. Special meaning is

sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row

or column, which are vectors.

Entering a Matrix:

You only must follow a few basic conventions:

• Use a semicolon ; to indicate the end of each row.

• Surround the entire list of elements with square brackets, [ ].

To enter matrix, simply type in the Command Window

MATLAB displays the matrix you just entered:

A=

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

Once you have entered the matrix, it is automatically remembered in the MATLAB

workspace. You can refer to it simply as A. Now that you have A in the workspace.

Sum

The first statement to try is

sum(A)

MATLAB replies with

ans =

34 34 34 34

When you do not specify an output variable, MATLAB uses the variable ans, short for

answer, to store the results of a calculation. You have computed a row vector containing the

sums of the columns of A. Each of the columns has the same sum, the magic sum, 34.

How about the row sums? MATLAB has a preference for working with the columns of a

matrix, so one way to get the row sums is to transpose the matrix, compute the column sums

of the transpose, and then transpose the result. For an additional way that avoids the double

transpose use the dimension argument for the sum function.

Transpose

MATLAB has two transpose operators. The apostrophe operator (e.g., A') performs a

complex conjugate transposition. It flips a matrix about its main diagonal, and also changes

the sign of the imaginary component of any complex elements of the matrix. The dot-

apostrophe operator (e.g., A.'), transposes without affecting the sign of complex elements.

For matrices containing all real elements, the two operators return the same result.

So

A'

produces

ans =

16 5 9 4

3 10 6 15

2 11 7 14

13 8 12 1

and

sum(A')'

produces a column vector containing the row sums

ans =

34

34

34

34

The sum of the elements on the main diagonal is obtained with the sum and the diag

functions:

diag(A)

produces

ans =

16

10

7

1

and

sum(diag(A))

produces

ans =

34

The other diagonal, the so-called antidiagonal, is not so important mathematically, so

MATLAB does not have a ready-made function for it. But a function originally intended for

use in graphics, fliplr, flips a matrix from left to right:

sum(diag(fliplr(A)))

ans =

34

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the

number in the fourth row and second column. For the magic square, A(4,2) is 15. So to

compute the sum of the elements in the fourth column of A, type

A(1,4) + A(2,4) + A(3,4) + A(4,4)

This subscript produces

ans =

34

but is not the most elegant way of summing a single column.

It is also possible to refer to the elements of a matrix with a single subscript, A(k). A single

subscript is the usual way of referencing row and column vectors. However, it can also apply

to a fully two-dimensional matrix, in which case the array is regarded as one long column

vector formed from the columns of the original matrix. So, A(8) is another way of referring to

the value 15 stored in A(4,2).

If you try to use the value of an element outside of the matrix, it is an error:

t = A(4,5)

Index exceeds matrix dimensions.

Conversely, if you store a value in an element outside of the matrix, the size increases to

accommodate the newcomer:

X = A;

X(4,5) = 17

X=

16 3 2 13 0

5 10 11 8 0

9 6 7 12 0

4 15 14 1 17

The colon, :, is one of the most important MATLAB operators. It occurs in several different

forms. The expression

1:10

is a row vector containing the integers from 1 to 10:

1 2 3 4 5 6 7 8 9 10

100:-7:50

is

100 93 86 79 72 65 58 51

and

0: pi/4:pi

is

Subscript expressions involving colons refer to portions of a matrix:

A(1:k,j)

sum(A(1:4,4))

Computes the sum of the fourth column. However, there is a better way to perform this

computation. The colon by itself refers to all the elements in a row or column of a matrix and

the keyword end refers to the last row or column. Thus:

sum(A(:,end))

ans =

34

Swap column

A = B( :, [1 3 2 4] )

This subscript indicates that—for each of the rows of matrix B—reorder the elements in the

order 1, 3, 2, 4. It produces:

A=

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

Concatenation

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made

your first matrix by concatenating its individual elements. The pair of square brackets, [], is

the concatenation operator. For an example, start with the 4-by-4 A Matrix, and form

The result is an 8-by-8 matrix, obtained by joining the four submatrices:

B=

16 3 2 13 48 35 34 45

5 10 11 8 37 42 43 40

9 6 7 12 41 38 39 44

4 15 14 1 36 47 46 33

64 51 50 61 32 19 18 29

53 58 59 56 21 26 27 24

57 54 55 60 25 22 23 28

52 63 62 49 20 31 30 17

Arrays

When they are taken away from the world of linear algebra, matrices become two-

dimensional numeric arrays. Arithmetic operations on arrays are done element by element.

This means that addition and subtraction are the same for arrays and matrices, but that

multiplicative operations are different. MATLAB uses a dot, or decimal point, as part of the

notation for multiplicative array operations.

The list of operators includes

+ Addition

- Subtraction

.* Element-by-element multiplication

./ Element-by-element division

.\ Element-by-element left division

.^ Element-by-element power

.' Unconjugated array transpose

Example

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

B= [5 6 10 12 1 5 11];

>> A+B

ans =

7 10 15 18 4 7 12

>> A-B

ans =

-3 -2 -5 -6 2 -3 -10

>> A.*B

ans =

10 24 50 72 3 10 11

>> A./B

ans =

>> A.\B

ans =

Conditional statements enable you to select at run time which block of code to execute. The

simplest conditional statement is if statement. For example:

% Generate a random number

a = randi(100, 1);

% If it is even, divide by 2

if rem(a, 2) == 0

disp('a is even')

b = a/2;

end

if statements can include alternate choices, using the optional keywords

else if or else. For example:

a = randi(100, 1);

if a < 30

disp('small')

elseif a < 80

disp('medium')

else

disp('large')

end

This section covers those MATLAB functions that provide control over program loops.

for

The for loop repeats a group of statements a fixed, predetermined number of times. A

matching end delineates the statements:

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

r(1)=A(1);

for n = 2:7

r(n) = r(n-1)+ A(n);

end

r

It is a good idea to indent the loops for readability, especially when they are nested:

for i = 1:4

for j = 1:4

H(i,j) = 1/(i+j);

end

end

While

The while loop repeats a group of statements an indefinite number of times under control of a

logical condition.

a=1;

b=1;

count=0

while a+b < 15

a=a+1;

b=b+1;

count=count+1;

end

count

Functions

A function is a group of statements that together perform a task. In MAT LAB, functions are

defined in separate files. The name of the file and of the function should be the same.

Functions can accept more than one input arguments and may return more than one output

arguments

Syntax of a function statement is:

function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)

Example

The following function named mysum should be written in a file named mysum.m. It takes

five numbers as argument and returns the sum of the numbers.

Create a function file, named mysum.m and type the following code in it:

%This function calculates the sum of the

% five numbers given as input

Sumval=n1+n2+n3+n4+n5;

end

The first line of a function starts with the keyword function. It gives the name of the function

and order of arguments. In our example, the mysum function has five input arguments and

one output argument.

The comment lines that come right after the function statement provide the help text. These

lines are printed when you type:

help mysum

MATLAB will execute the above statement and return the following result:

This function calculates the sum of the five numbers given as input

You can call the function in main file as:

mysum(34, 78, 89, 23, 11)

MATLAB will execute the above statement and return the following result:

ans =

235

Anonymous Functions

An anonymous function is like an inline function in traditional programming languages,

defined within a single MATLAB statement. It consists of a single MATLAB expression and

any number of input and output arguments.

You can define an anonymous function right at the MATLAB command line or within a

function or script.

This way you can create simple functions without having to create a file for them.

The syntax for creating an anonymous function from an expression is

f = @(arglist)expression

Example

In this example, we will write an anonymous function named power, which will take two

numbers as input and return first number raised to the power of the second number.

Create a script file and type the following code in it:

power = @(x, n) x.^n;

result1 = power(7, 3)

result2 = power(49, 0.5)

result3 = power(10, -10)

result4 = power (4.5, 1.5)

When you run the file, it displays:

result1 =

343

result2 =

7

result3 =

1.0000e-10

result4 =

9.5459

Command summary

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] // matrix entry

sum(A) sum of all column

A' transpose

sum(A')' sum transpose

diag(A) Diagonal

sum(diag(fliplr(A))) Flip left to right

A(1,4) Select element 1 row 4 column

D=100:-7:50

A(1:k,j) 1 to k row of jth column

A(:,end) All rows of last column

B(:,[1 3 2 4]) Swapping column

B = [A A+32; A+48 A+16] Concatenation

If elseif If and elseif statement

while while loop

function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN) function

f = @(arglist)expression Anonymous Functions

y = cos(x)

z=x

for 0 ≤ x ≤ 2 in the same window. Use the zoom facility to determine the point of intersection

of the two curves (and, hence, the root of x = cos(x)) to two significant figures.

plots!

y = t sin (3t)

input numbers. Output of this function should be highest of these numbers.

[1,2,3;4,5,6;7,8,9].The function should perform following task

i) Add row1 and row3

ii) subtract row3 from row3

iii) multiply row1 and row2

iv) Divide row2 by row1

Note: - Function should be generic and perform on any 3x3 matrix

POST Lab 01

• Question#1: Draw following signal in Matlab in one figure and also give legend to

them for differentiated.

i) Sin(2πt)

3

ii) Cos(2πt)

3

iii) Sin(2πt)+ Cos(2πt)

Where 0≤ t ≤ 5

Question#2: Make a function m that can add two numbers (A and B). Write a program which

get input form user and by using function (addfunction which you create) add these two

number.

Question#3: write a function whose input is 8x8 matrix. Output of this function is

highest value of element in matrix and position (Row and column no) of that element.

Example

A= 5 8 9 20

6 2 7 2

1 2 8 9

2 7 11 19

Output should be highest element=20, row=1, column=4

matrix [5,2,6;3,5,1;7,5,9].The function should perform following task

1. Add diagonal elements and column1

2. Multiply diagonal elements and column3

- CXC 1993Uploaded bymadman26495732
- MatlabUploaded byp_odunga
- Propiedades Extremas de Valores Propios TropicalesUploaded byWendy Villogas Espinoza
- L01.pdfUploaded byarsyafin7
- ES440F90Lab1_24jan08Uploaded bygetsweet
- Intro MatlabUploaded byVictor Nunes
- MAT FemInglesUploaded byhoneyb
- Linear Algebra Spring 2015Uploaded bysofi
- Excel FunctionsUploaded byAndreea Rancea
- Lab ManualUploaded bysaniljayamohan
- DeterminantsUploaded byapi-20012397
- Data AnalysisUploaded byJefferson Saraiva
- Maths UlangkajiUploaded bychehor
- CCPL 1C PradeepUploaded bypradeepkraj22
- Matlab CourseUploaded byAzrin Kun
- Introduction to MATLABUploaded byjunaidmyousuf
- Efecto Stark LinealUploaded byunomas9579
- Code PoolUploaded bynsitdce
- Matlab Mini ManualUploaded byumitgurluk2792
- business_maths_chapter_3.docxUploaded by鄭仲抗
- Speeding Up Your CodeUploaded byZiad Qais
- c code.docxUploaded byPranjal Jalan
- Stability and Plant WideUploaded byAlifDzaki
- If the Marks Obtained by a Student in Five Different Subjects Are Input Through the KeyboardUploaded byimtishal_ali3263
- Codigo ListUploaded byJosé Walter Losada Cabrera
- problemUploaded byRakib Ahsan
- Multidimensional 2D ArraysUploaded byDoula Isham
- Cond Sum ArrayUploaded byapi-26344229
- 2015–16_Senior School Mathematics (1)Uploaded byJyoti Bhola

- EMS Lab Manual Ver 1.0 (Fall 2016)Uploaded byFahad Mahmood
- Lecture on BVPUploaded byarafatasghar
- lec 10 gauss elimination1.pptUploaded byFahad Mahmood
- lec 9 other methods.pptUploaded byFahad Mahmood
- lec 6 mathlab2.pptUploaded byFahad Mahmood
- lab 7Uploaded byFahad Mahmood
- Internship Policy EE StudentsUploaded byFahad Mahmood
- CAO Assignment#2Uploaded byFahad Mahmood
- LCS Lab 9Uploaded byFahad Mahmood
- DSP Lab 3Uploaded byFahad Mahmood
- lab 1Uploaded byFahad Mahmood
- Call for Internship - Final VersionUploaded byFahad Mahmood
- Mazar e QuaidUploaded byFahad Mahmood
- EssayUploaded byFahad Mahmood
- 01 Introduction Microprocessor and InterfaceUploaded byFahad Mahmood
- LCS Lab 2 (Spring 2018) (1)Uploaded byFahad Mahmood
- Eligibility Criteria for Different Positions (1)Uploaded byFahad Mahmood
- lab 1Uploaded byFahad Mahmood
- CS MATLAB AssignmentUploaded byFahad Mahmood
- SNS Lab 4Uploaded byFahad Mahmood
- BE lab 7 picsUploaded byFahad Mahmood
- Chapter 1Uploaded byFahad Mahmood
- BE lab 5Uploaded byFahad Mahmood
- WaleedUploaded byFahad Mahmood
- Assignment 3Uploaded byFahad Mahmood
- Lecture 1bUploaded byFahad Mahmood

- The History of Modern Science and MathematicsUploaded byRaavan Ragav
- A Breif Introduction to the Fractional Fourier TransformUploaded byIan Hoover
- Pertran - A Transport-perturbation ProgramUploaded byAnisur Rahman Ripon
- Section 5 (PreCalculus)Uploaded byRodrigo Valdecantos
- CONJUGATES AND DIVISION OF COMPLEX NUMBERSUploaded byMike Yaranga Acori
- AAOC_C341Uploaded byVignesh_23
- TrignometryUploaded bygargatwork
- Chapter 01 Analysis of StressUploaded bybudi susilo
- VectorsUploaded byboi
- Truss 3d ExampleUploaded byangegkar
- Definitions and Basics TRIGNOMETRYUploaded byMohd Qureshi
- Definition of MatrixUploaded byGilbert Bersola
- NMP SUGGESTIONUploaded byParidhi Babel
- Curso de MatlabUploaded byCarlos Puchaicela
- The William Lowell Putnam Mathematical Competition Problems & Solutions, 2001-2008Uploaded byFernandoDiaz
- UCE Book 3Uploaded byAnonymous elACfG
- College Algebra and TrigonometryUploaded byapi-3699443
- NIMCET MCA Entrance 2012 SolutionsUploaded byarchie_ashley
- Math of PhotogrammetryUploaded byKen Lim
- Vector Fields on SpheresUploaded byblexim
- Number theory for beginners - Weil A..pdfUploaded byLuisa Fernanda Rojas
- Beam BucklingUploaded bySaleha Quadsia
- CAPE Pure Mathematics SyllabusUploaded byDarnell Gracen
- [1] Developments in Nonholonomic Control ProblemsUploaded byHai Nguyen Thanh
- Diagnostic Test in College Algebra for Freshman Non-Education Students of Westmead International School: Input to Proposed Remedial ActivitiesUploaded byAsia Pacific Journal of Multidisciplinary Research
- 07_SVD_RGA_CTS.pptUploaded bySreekanthMylavarapu
- PartI2008.pdfUploaded bySahabudeen Salaeh
- Lesson Plan RevisiUploaded byIsolihatun Nurcipto
- Cs.theorists.toolkitUploaded byJohn Le Tourneux
- Taylan Bilal- Heegard Floer HomologyUploaded byCore0932