You are on page 1of 16

EXPERIMENT 01

Two Dimensional Graphs & Matrix Implementation in Matlab

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:

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


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

>> plot (t, y)


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

Figure1.1 Plot of Sin(3*pi*t)

On changing the value of N to 100:


>> 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

Figure 1.2 y=sin3(pi)t for 0 ≤ t ≤ 1using h=0.001

Plotting—Titles & Labels:


To put a title and label the axes, we use

>> title (’Graph of y =sin(3pi t)’)


>> 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.

Line Styles & Colors:


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

>> plot (t, y, ’w-’)


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:

Colors Line Style

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:

>> plot (t, y, ’r-’,t, cos (2*pi*t), ’g--’)


A descriptive legend may be included with

>> legend (’Sin curve’, ’Cos curve’)


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

>> plot (t, y, ’r-’, t, cos (2*pi*t), ’g--’)

>> legend (’Sin curve’, ’Cos curve’)

>> title (’Multi-plot ’)

>> xlabel (’x axis(time)’), ylabel (’y axis’)

>> 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

Figure 1.3 Plot of y = sin(3*pi*t) and y = cos(3*pi*t) for 0≤ t ≤1 with h=0.001


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, ’w-’), hold


>> 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.

>> subplot (221), plot (t,y)


>> 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

Figure 1.4 Sin and cos graph

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

Right-Click on plot = Zoom out

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.

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


>> 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

-0.5 0 0.5 1 1.5

Figure 1.5 Effect of setting axis

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)’)

Figure1.6 Plotting of different function

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

>> subplot(222),axis([0 10 0 10])


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

Example: Draw graphs of sin(nπx) on the interval -1 ≤ x ≤ 1 for n = 1, 2, . . ., 8.

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

>> for counter =[23 11 19 5.4 6]


.......
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.)

 Matrices and Arrays


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:

• Separate the elements of a row with blanks or commas.


• 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

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


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, transpose, and diagonal


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 Operator


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

To obtain non-unit spacing, specify an increment. For example,


100:-7:50
is
100 93 86 79 72 65 58 51
and
0: pi/4:pi
is

0 0.7854 1.5708 2.3562 3.1416


Subscript expressions involving colons refer to portions of a matrix:

A(1:k,j)

is the first k elements of the jth column of A. Thus:


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))

computes the sum of the elements in the last column of A:

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

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


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 =

0.4000 0.6667 0.5000 0.5000 3.0000 0.4000 0.0909


>> A.\B

ans =

2.5000 1.5000 2.0000 2.0000 0.3333 2.5000 11.0000

Conditional Control — if, else, switch


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

Loop Control — for and while loop


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:

function sumval = mysum(n1, n2, n3, n4, n5)


%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

C=1:10 creating array


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

for for loop


while while loop
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN) function
f = @(arglist)expression Anonymous Functions

Lab Task 01:

Question#1 Draw graphs of the 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.

Question#2 Draw graphs of exp(nx) on the interval -1 ≤ x ≤ 1 for n = 1, 2, . ., 8. Use Sub-


plots!

Question#3 Make a function to generate:

y = t sin (3t)

where t is an input by the user to the function

Question#4: Write a function “highestnumber (a,b,c,d,e)” where a, b, c, d and e are


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

Question#5: Write a function “rowoperation(A)” where A is 3x3 matrix


[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.

A input form user

B input form user

Y=addfunction(A,B) //function that you have to create

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

Question#4: Question 2: Write a function “diagonaloperation(A)” where A is 3x3


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