0% found this document useful (0 votes)
58 views13 pages

Lab 2

The document discusses plotting graphs in MATLAB using commands like plot, subplot, and hold on. It provides examples of plotting multiple graphs on the same axis, using subplots to plot multiple sets of axes, and different plot styles like logarithmic, stairs, and stem plots. It also discusses commands for displaying text and taking user input in MATLAB programs.

Uploaded by

ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
58 views13 pages

Lab 2

The document discusses plotting graphs in MATLAB using commands like plot, subplot, and hold on. It provides examples of plotting multiple graphs on the same axis, using subplots to plot multiple sets of axes, and different plot styles like logarithmic, stairs, and stem plots. It also discusses commands for displaying text and taking user input in MATLAB programs.

Uploaded by

ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

LAB 2 PART(A): MATLAB REVIEW (PLOTTING)

CLO5: USE MODERN TOOL (E.G. MATLAB) FOR SIGNAL REPRESENTATION, VISUALIZATION AND
PROCESSING IN BOTH TIME AND FREQUENCY DOMAIN .

1. Plotting Graphs:
Plotting in MATLAB is done by command plot(x values, y values, ‘style option’). It is important to
note that x-values and y-values should have same size. ‘Style Option’ is optional. It is usually used
when you are plotting more than one plot on same axis. Different style options are listed below:

Color style-option Line style-option Marker style-option


y Yellow – Solid + Plus sign
m Magenta –– Dashed O circle
c Cyan : Dotted * Asterisk
r Red –. Dash-dot x x-mark
g Green . Point
b Blue ^ Up triangle
w White s Square
K Black d diamond

The other commands which are helpful in plotting are:


xlabel(‘abc’) →labels x-axis with name specified, abc in this case.
ylabel(‘xyz’) →labels y-axis with name specified, xyzin this case.
title(‘abc’)→ generates title of the graph with name specified, abc in this case.
axis[x1 x2 y1 y2]→Set the axis as specified (x-axis from x1 to x2 and y-axis from y1 to y2).
text(x,y,’abc’)→Labels point(x,y) on graph with name specified abc in this case.
gtext(‘xyz’)→This command is used to label some point on graph selecting that point by clicking
mouse and specified name will be labeled, xyz in this case. If you r using this command more than
one in script file, first click will label the name specified in first command and then second click
will label name specified in second command and so on.
grid→makes a grid on plot.
How to plot more than one graph on same axis:
You can plot as many graphs on same axis as you want using plot(x1,y1,x2,y2……)
Let’s see an example:
Run following instructions on a script M-File:
t = linspace(0, 2 * pi, 100);%(if you have no idea of linspace, search on
help)
y1 = sin(t); y2 = t;
y3 = t - (t.^ 3)/6 + (t.^ 5)/120 - (t.^ 7)/5040;
plot(t,y1,t,y2,'-',t,y3,'--')
axis([0 5 -1 5])
xlabel('t')
ylabel('sin(t) approximation')

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
title('sin(t) function')
text(3.5, 0, 'Point')
gtext('Linear Graph separates')
gtext('Sin Graph Separates')
grid
legend('y1','y2','y3')
Another way to plot multiple graphs on same axis is using hold on and plotting each graph
separately, all graph will be plotted on same axis. You can turn off hold using hold off command.

Test Yourself
Plot above three graphs using hold on command:

Subplots:
You can hold more than one set of axes on one figure window. The command subplot(m,n,p)
subdivides the current figure window into an m-by-n matrix of plotting areas and chooses the pth
area to be active.
Test Yourself
Run following commands and plot the output:
x = -2*pi:pi/10:2*pi;
y = x.^2;
z = sin(x);
y1 = cos(x);
z1 = exp(x);
subplot(2,2,1),plot(x,y)
grid
subplot(2,2,2),plot(x,z)
grid
subplot(2,2,3),plot(x,y1)
grid
subplot(2,2,4),plot(x,z1)
grid
(write instructions for axis label, graph title by yourself)

Note: After using subplot commands, if you again want to view single graph, use clf (Clear Figure)
command.
Logarithmic Scale Graphs:
Graphs can also be plotted on Logarithmic Scale. Commands are:
loglog→Both axis Logarithmic Scale
semilogx→ x-axis Logarithmic Scale
semilogy→ y-axis Logarithmic Scale

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
Some Other x-y Plotting:
Some other techniques of plotting x-y graphs are listed below. Explore them by yourself if you are
interested.

Function Description
area Creates a filled area plot
bar Creates a bar graph
barh Creates a horizontal bar graph
comet Makes an animated 2-D plot
compass Creates arrow graph for complex numbers
contour Makes contour plots
contourf Makes filled contour plots
errorbar Plots a graph and puts error bars

Function Description
feather Makes a feather plot
fill Draws filled polygons of specified color
fplot Plots a function of single variable
hist Makes histograms
loglog Creates plot with log scale on both x and y axes
pareto Makes pareto plots
pcolor Makes pseudo color plot of matrix
pie Creates a pie chart
plotyy Makes a double y-axis plot
plotmatrix Makes a scatter plot of a matrix
polar Plots curves in polar coordinates
quiver Plots vector fields
rose Makes angled histograms
scatter Creates a scatter plot
semilogx Makes semi-log plot with log scale on the x-axis
semilogy Makes semi-log plot with log scale on the y-axis
stairs Plots a stair graph
stem Plots a stem graph

The last two are commonly used.


Test Yourself
Use stairs and stem plots to plot a graph of 𝐬𝐢𝐧 𝟐𝒙 𝐜𝐨𝐬 𝒙 where x is from 0-2π

2. Display commands in Programming:


If you want to display some message at output, simple command is output
For example if you write following code in M-file, the statement in quotes will be displayed.

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
display('We are learning MATLAB');

There is one more command fprinf for output. It has more variety of options. Explore it by
yourself by doc fprintf

If you want to take input from user, simple command input is used. You can also display some
message while taking the input. For example if you write in M-File:
a=input('Enter first digit:')

The message in quotes will be printed, user will enter an input that will be stored in variable a.

Test Yourself
Write a M-File program that will ask user for two input digits one by one and then will ask what
is sum of those numbers. If the sum is correct, it will print “Correct” and otherwise it will print
“Wrong”. (If you wish you can also extend it so that program should keep on asking the sum till it
gets the correct sum)
A sample output is :
What number is a: 15
What number is b: 20
What is the sum of a + b: 35
answer = Correct!
M-File code Output

While Loop:
Syntax of while loop is similar to for loop:
while expression
statements

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
end

In for loop number of repetitions are known, but if you are facing condition that number of
repetitions are not known, then while loop is used.
Here is an almost trivial problem that requires a use of this loop. Suppose that the number π is
divided by 2. The resulting quotient is divided by 2 again. This process is continued till the current
quotient is less than or equal to 0.01. What is the largest quotient that is greater than 0.01?
To answer this question code will be:
q = pi;
while q > 0.01
q = q/2;
end
q

And the output is:


q=
0.0061

Switch-case constructions
Syntax of the switch-case construction is
switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)
commands
case value2 (executes if expression evaluates to value2)
commands
.
.
.
otherwise
statements
end

Switch compares the input expression to each case value. Once the match is found it executes
the associated commands.

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
For example a random integer number x from the set {1, 2, … , 10} is generated. If x = 1 or x = 2,
then the output is 20. If x = 3 or 4 or 5, then the output is 30, otherwise the output is 50.
x = ceil(10*rand % rand generates random from 0 to 1 so x is from 1 to 10 (Got
it??)
switch x
case {1,2}
a=20;
case {3,4,5}
a=30;
otherwise
a=50;
end
x
a

3. Display commands in Programming:


If you want to display some message at output, simple command is output
For example if you write following code in M-file, the statement in quotes will be displayed.
display('We are learning MATLAB');

There is one more command fprinf for output. It has more variety of options. Explore it by
yourself by doc fprintf

If you want to take input from user, simple command input is used. You can also display some
message while taking the input. For example if you write in M-File:
a=input('Enter first digit:')

The message in quotes will be printed, user will enter an input that will be stored in variable a.

Test Yourself
Write a M-File program that will ask user for two input digits one by one and then will ask what
is sum of those numbers. If the sum is correct, it will print “Correct” and otherwise it will print
“Wrong”. (If you wish you can also extend it so that program should keep on asking the sum till it
gets the correct sum)
A sample output is :
What number is a: 15
What number is b: 20
What is the sum of a + b: 35
answer = Correct!

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
PRACTICE PROBLEMS
These problems are taken from Cody Challenges at Mathworks website. The problems numbers
mentioned in some of the task are also from the same challenge. I am literally using Ctrl+C and Ctrl+V
to make this HW.
It is better to practice find function before attempting these problems. You can write >>doc find in
command window to get details.

1. Problem 1786. Create an index-powered


vector
Given a input vector x, return y as index-powered vector as shown below.

Example

x = [2 3 6 9]

then y should be

[2^1 3^2 6^3 9^4] = [2 9 216 6561]

2. Find nth maximum in a vector of integer


numbers. Return NaN if no such number
exists.
x = [2 6 4 9 -10 3 1 5 -10];

So

• n_max(x,3) would find 3rd maximum value in x which is 5


• n_max(x,8) would find 8th maximum value in x which is -10
• n_max(x,9) would find 9th maximum value in x which is -10
• n_max(x,12) does not exist so return NaN

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
3. Determine whether the vector is
symmetric or not (vector could be even
or odd in length).
For example:

x = [1 2 3 3 2 1] is symmetric

x = [1 2 3 4 3 2 1] is symmetric as well!

x = [-1 -2 -3 3 2 1] is not symmetric

4. Insert zeros after each elements in the


vector. Number of zeros is specified as
the input parameter.
For example:

x = [1 2 3 4 5]

y = insert_zeros(x,2) % two zeros need to be inserted after each element

y_correct = [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0];

5. Problem 1779. Oh Zero Zero Zero!!!


You have to find the largest section of zeros in a vector and then find the length of those zeros
and there starting position... For example:

x = [1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 9 8 7 6 5 4 3 2 1];

%then the output is:

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
LP = [9 10] %[Length Position]

%Or another example:

x = [1 0 3 49 3 2 232 3 0 0 0 0 0 0 8 290 0 0 0 12 323 34];

%then the output is:

LP = [6 9]

%Or another example:

x = [1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0];

%then the output is:

LP = [7 3];

6. Problem 1430. Create an n-by-n null


matrix and fill with ones certain positions
The positions will be indicated by a z-by-2 matrix. Each row in this z-by-2 matrix will have the
row and column in which a 1 has to be placed.

Example:

n=3;

mat=[1 3; 2 1]; --> We want A(1,3)=1 and A(2,1)=1

A = FillWithOnes(n,mat);

A=[0 0 1; 1 0 0; 0 0 0];

7. Problem 1038. Change the sign of even


index entries of the reversed vector
change the signs of the even index entries of the reversed vector

example 1 vec = [4 -1 -2 9] ans = [9 2 -1 -4]

example2 vec = [-4 -1 -2 -9] ans = [-9 2 -1 4]

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
8. Problem 1229. Determine the number of
odd integers in a vector
Determine the number of unique odd integers in a vector.

Examples:

Input x = [2 5 8 3 7 1];

Output y = 4;

Input x = [2 5 9];
Output y = 2;

9. Problem 1035. Generate a vector like


1,2,2,3,3,3,4,4,4,4
Generate a vector like 1,2,2,3,3,3,4,4,4,4

So if n = 3, then return

[1 2 2 3 3 3]

And if n = 5, then return

[1 2 2 3 3 3 4 4 4 4 5 5 5 5 5]

10. Problem 792. Set some matrix elements


to zero
First get the maximum of each row, and afterwards set all the other elements to zero. For
example, this matrix:

1 2 3 4

5 5 6 5

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
7 9 8 3

should become:

0 0 0 4

0 0 6 0

0 9 0 0

Input will never be empty.

If a row has the same maximum in different columns , display the first occurrence:

In the below example, the second row has twice the number 8 as maximum , the output will
display the first 8 (column2) :

x =

5 4 5

2 8 8

should become :

5 0 0
0 8 0

11. Problem 611. surrounded matrix


With a given matrix A (size m x n) create a matrix B (size m+2 x n+2) so that the matrix A is
surrounded by ones:

A = [1 2 3

3 2 1]

B = [1 1 1 1 1

1 1 2 3 1

1 3 2 1 1

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
1 1 1 1 1]

or

A = 4

B = [ 1 1 1
1 4 1
1 1 1]

12. Problem 1632. Calculate the Number of


Sign Changes in a Row Vector (No
Element Is Zero)
For a row vector:

V=[7 1 2 -3]

there is one sign change (from 2 to -3). So, the function you write must return N=1.

For this row vector:

V=[5 9 -2 7];

there are two sign changes, one from 9 to -2 and a second from -2 to 7, thus N=2.

Similarly

V=[-4 -6 -7 -5 -6] and V=[3 7 6 5 6 7 8 7 6]

have no sign changes (N=0).

13. Problem 888. Create a vector whose


elements depend on the previous
element
The idea is to create a vector A whose elements depend on the previous element : A(i+1) =
2*A(i)+1

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore
2 Inputs:

- A : The first value of the vector

- iterations : The number of iterations

1 Output:

- A a vector with iterations+1 elements such as the i+1 element depend on the previous
element as follows :

A(i+1) = 2*A(i)+1

Example :

A = 1;

iterations = 4;

The expected output vector has 5 elements :

A = [1 3 7 15 31]

A(2) =3 because A(2) =2*A(1)+1 = 2*1+1 = 3

A(3) = 7 because A(3) =2*A(2)+1 ...

MCT-301L: Signals and Systems


Department of Mechatronics and Control Engineering, U.E.T Lahore

You might also like