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:
>> y =sin(3*pi*t);
and finally, we can plot the points with
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
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
Grids:
A dotted grid may be added by
>> grid
This can be removed using either grid again, or grid off.
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:
>> 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
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.
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.
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.
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
Entering a Matrix:
You only must follow a few basic conventions:
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
A(1:k,j)
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
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 =
ans =
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:
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
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.
y = t sin (3t)
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