LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h...

11
Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 1 LAB No. 2 Introduction to Matlab - Functions and Plotting Objective: The objective of this lab is to have a complete command over Matlabs’ commonly used built- in functions, user defined functions and plotting capabilities. Graphics in Matlab Plotting Functions Matlab has range of built-in graphics and plotting routines. The command plot(x,y) makes a two dimensional plot of x against y. For example, x = -20:0.01:20; y = sin(x)./x; plot(x,y); “This Graph is called Sinc function divided by x between -20 and 20. The points of the x axis are separated by 0:01; for different spacing, you would use a different increment in the colon operator in the definition of x.” Type help plot at the prompt to get a description of the use of the plot function. Your math teacher may have taught you to always label your axes; here is how: xlabel and ylabel puts strings on the axes, like so, xlabel('x'); ylabel('sin(x)/x'); To get rid of the figure, type close at the Matlab prompt. COLOR POINT STYLE LINE STYLE character color character symbol character line-style B blue . point - solid G green o circle : dotted

Transcript of LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h...

Page 1: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 1

LAB No. 2 Introduction to Matlab - Functions and

Plotting

Objective: The objective of this lab is to have a complete command over Matlabs’ commonly used built-

in functions, user defined functions and plotting capabilities.

Graphics in Matlab

Plotting Functions

Matlab has range of built-in graphics and plotting routines. The command plot(x,y) makes a

two dimensional plot of x against y. For example,

x = -20:0.01:20; y = sin(x)./x; plot(x,y); “This Graph is called Sinc function divided by x

between -20 and 20. The points of the x axis are

separated by 0:01; for different spacing, you would use

a different increment in the colon operator in the

definition of x.”

Type help plot at the prompt to get a description of the

use of the plot function. Your math teacher may have

taught you to always label your axes; here is how:

xlabel and ylabel puts strings on the axes, like so,

xlabel('x'); ylabel('sin(x)/x'); To get rid of the figure, type close at the Matlab

prompt.

COLOR POINT STYLE LINE STYLE

character color character symbol character line-style

B blue . point - solid

G green o circle : dotted

Page 2: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 2

R red x x-mark -. dash-dot

C cyan + plus - dashed

M magenta * star

Y yellow s square

K black d diamond

v triangle(down)

^ triangle(up)

> triangle(right)

< triangle(left)

p pentagram

h hexagram

For example, if we wanted to plot the graphs above as crosses in red, the command

would be

plot(x,y,'r+');

Create line plot using specific line width, marker color, and marker size:

x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); plot(x,y,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)

Modify axis tick marks and tick labels:

x = -pi:.1:pi; y = sin(x); plot(x,y) set(gca,'XTick',-pi:pi/2:pi) set(gca,'XTickLabel',{'-pi',...

Page 3: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 3

'-pi/2','0','pi/2','pi'})

Add a plot title, axis labels, and annotations:

clear all; close all; clc x = -pi:.1:pi; y = sin(x); p = plot(x,y); set(gca,'XTick',-pi:pi/2:pi) set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'}) xlabel('-\pi \leq \Theta \leq \pi') ylabel('sin(\Theta)') title('Plot of sin(\Theta)') % \Theta appears as a Greek symbol (see String in Matlab help) % Annotate the point (-pi/4, sin(-pi/4)) text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',... 'HorizontalAlignment','left') % Change the line color to red and % set the line width to 2 points set(p,'Color','red','LineWidth',2); grid

Multiple Plots If you want to compare plots of two different functions, calling plot twice in succession will

not be satisfactory, because the second plot will overwrite the first. You can ensure a new

plot window for a plot by calling figure first.

-pi -pi/2 0 pi/2 pi-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

-

sin

( )

Plot of sin()

sin(-4)

Page 4: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 4

If you want to put multiple plots on the same figure, we set hold on. The default is hold off,

which makes a new figure overwrite the current one. Here is an example. Suppose we want

to compare the log function with the square root function graphically. We can put them on

the same plot. By default, both plots will appear in blue,

so we will not know which is which. We could make

them different colors using options. Here is the final

answer, x=1:100; y=log(x); z=sqrt(x); plot(x,y,'r'); % plot log in red hold on; plot(x,z,'b'); % plot log in blue hold off;

What appears after the % on a line is a comment. The options can also be used to plot the

values as points rather than lines. For example, '+' plots a cross at each point, '*' a star and

so forth. So, x=1:100; y=log(x); z=sqrt(x); plot(x,y,'r+'); % plot log as red crosses hold on; plot(x,z,'b*'); % plot log as blue stars hold off;

Sub-plotting

More than one plot can be put on the same figure using the subplot command.

The subplot command allows you to separate the figure into as many plots as desired, and

put them all in one figure. To use this command, the following line of code is entered into the

Matlab command window or an m-file:

subplot(m,n,p)

This command splits the figure into a matrix of m rows and n columns, thereby creating m*n

plots on one figure. The p'th plot is selected as the currently active plot. For instance, suppose

you want to see a sine wave, cosine wave, and

tangent wave plotted on the same figure, but

not on the same axis. The following m-file will

accomplish this:

x = linspace(0,2*pi,50); y = sin(x); z = cos(x); w = tan(x);

Page 5: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 5

subplot(2,2,1) plot(x,y) subplot(2,2,2) plot(x,z) subplot(2,2,3) plot(x,w)

Three-Dimensional Plots These will not be used for this course, but you can also make three dimensional plots. If you

have three dimensional data, such as

data = 5.1000 3.5000 1.4000

4.9000 3.0000 1.4000

4.7000 3.2000 1.3000

4.6000 3.1000 1.5000

5.0000 3.6000 1.4000

5.4000 3.9000 1.7000

4.6000 3.4000 1.4000

5.0000 3.4000 1.5000

This could be plotted as points in 3-d, using the plot3 command,

plot3(data(:,1),data(:,2),data(:,3),'+')

You can rotate the plot around. You can also plot functions of two

variables. An example of this can be seen with the following [x,y] = meshgrid(-8:.5:8); r = sqrt(x.^2+y.^2) + eps; z = sin(r)./r; surf(x,y,z);

You can click on the icon which looks like a circular arrow, and

rotate the plot around using the mouse. To learn about using Matlab to make all types of

plots, see “Graphics" under the “Getting Starting" and under the “Using Matlab" in the on-

line help. For a list of commands, type help graph2d or graph3d at the Matlab prompt.

Scripts and functions An M-file is a plain text file containing MATLAB commands and saved with the filename

extension “.m”. There are two types; a) scripts and b) functions. MATLAB comes with a pretty

good editor that is tightly integrated into the environment; start it by typing edit with a file

name. However, you are free to use any text editor.

An M-file should be saved in the path in order to be executed. The path is just a list of

directories folders) in which MATLAB will look for files. Use editpath or menus to see and

change the path. There is no need to compile either type of M-file. Simply type in the name

Page 6: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 6

of the file (without the extension) in order to run it. Changes that are saved to disk will be

included in the next call to the function or script. (You can alter this behavior with mlock.)

One important type of statement in an M-file is a comment, which is indicated by a percent

sign %. Any text on the same line after a percent sign is ignored (unless % appears as part of

a string in quotes). Furthermore, the first contiguous block of comments in an M-file serves

as documentation for the file and will be typed out in the command window if help is used

on the file.

Using scripts effectively The contents of a script file are literally interpreted as though they were typed at the prompt.

In fact, some people prefer to use MATLAB exclusively by typing all commands into scripts

and running them. Good reasons to use scripts are

Creating or revising a sequence of more than four or five lines.

Reproducing or rereading your work at a later time.

Functions Functions are the main way to extend the capabilities of MATLAB. Compared to scripts, they

are much better at compartmentalizing tasks. Each function starts with a line such as

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

The variables in1, etc. are input arguments, and out1 etc. are output arguments. You can

have as many as you like of each type (including zero) and call them whatever you want. The

name myfun should match the name of the disk file.

Here is a function that implements (badly, it turns out) the quadratic formula.

function [x1,x2] = quadform(a,b,c) d = sqrt(bˆ2 - 4*a*c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a);

From MATLAB you could call >> [r1,r2] = quadform(1,-2,1) r1 = 1

r2 = 1

One of the most important features of a function is its local workspace. Any arguments or

other variables created while the function executes are available only within the function.

Conversely, the variables available to the command line (the so-called base workspace) are

normally not visible to the function. If during the function execution, other functions are

called, each of those calls also sets up a private workspace. These restrictions are called

Page 7: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 7

scoping, and they make it possible to write complex programs without worrying about name

clashes. The values of the input arguments are copies of the original data, so any changes you

make to them will not change anything outside the function’s scope. In general, the only

communication between a function and its caller is through the input and output arguments.

You can always see the variables defined in the current workspace by typing who or whos.

Another important aspect of function M-files is that most of the functions built into MATLAB

(except core math functions) are themselves M-files that you can read and copy. This is an

excellent way to learn good programming practice.

Conditionals: if and switch Often a function needs to branch based on runtime conditions. MATLAB offers structures for

this similar to those in most languages.

Here is an example illustrating most of the features of if. if isinf(x) | ˜isreal(x) disp(’Bad input!’) y = NaN; elseif (x == round(x)) && (x > 0) y = prod(1:x-1); else y = gamma(x); end

The conditions for if statements may involve the relational operators, or functions such as

isinf that return logical values. Numerical values can also be used, with nonzero meaning

true, but “if x˜=0” is better practice than “if x”. Note also that if the if clause is a nonscalar

array, it is taken as true only when all the elements are true/nonzero. To avoid confusion,

it’s best to use any or all to reduce array logic to scalar values.

Individual conditions can be combined using & (logical AND) | (logical OR) ˜ (logical NOT)

Compound logic in if statements can be short-circuited. As a condition is evaluated from left

to right, it may become obvious before the end that truth or falsity is assured. At that point,

evaluation of the condition is halted. This makes it convenient to write things like

if (length(x) > 2) & (x(3)==1) ...

that otherwise could create errors or be awkward to write.

The if/elseif construct is fine when only a few options are present. When a large number of

options are possible, it’s customary to use switch instead. For instance:

switch units case 'length' disp('meters') case 'volume' disp('liters')

Page 8: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 8

case 'time' disp('seconds') otherwise disp('I give up') end The switch expression can be a string or a number. The first matching case has its commands

executed. If otherwise is present, it gives a default option if no case matches.

Loops: for and while Many programs require iteration, or repetitive execution of a block of statements. Again,

MATLAB is similar to other languages here. This code illustrates the most common type of

for loop:

>> f = [1 1]; >> for n = 3:10 f(n) = f(n-1) + f(n-2); end

You can have as many statements as you like in the body of the loop. The value of the index

n will change from 3 to 10, with an execution of the body after each assignment. But

remember that 3:10 is really just a row vector. In fact, you can use any row vector in a for

loop, not just one created by a colon. For example,

>> x = 1:100; s = 0; >> for j = find(isprime(x)) s = s + x(j); end

This finds the sum of all primes less than 100.

A warning: If you are using complex numbers, you might want to avoid using i as the loop

index. Once assigned a value by the loop, i will no longer equal √−1. However, you can always

use 1i for the imaginary unit. It is sometimes necessary to repeat statements based on a

condition rather than a fixed number of times. This is done with while.

while x > 1 x = x/2; end

The condition is evaluated before the body is executed, so it is possible to get zero

iterations. It’s often a good idea to limit the number of repetitions, to avoid infinite loops (as

could happen above if x is infinite). This can be done using break.

n = 0; while x > 1 x = x/2; n = n+1; if n > 50, break, end

Page 9: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 9

end

A break immediately jumps execution to the first statement after the loop.

Debugging and profiling To debug a program that doesn’t work, you can set breakpoints in one or more functions.

(See the Debug menu in the Editor.) When MATLAB reaches a breakpoint, it halts and lets

you inspect and modify all the variables currently in scope—in fact; you can do anything at

all from the command line. You can then continue execution normally or step by step. It’s

also possible to set non-specific breakpoints for error and warning conditions, for this you

can see the help on debug (or explore the menus) for all the details. Sometimes a program

spends most of its running time on just a few lines of code. These lines are then obvious

candidates for optimization. You can find such lines by profiling, which keeps track of time

spent on every line of every function. Profiling is also a great way to determine function

dependencies (who calls whom). Get started by entering profile viewer, or find the Profiler

under the Desktop menu.

General Information

MATLAB is case sensitive so "a" and "A" are two different names.

Comment statements are preceded by a "%".

Help for MATLAB can be reached by typing helpdesk or help for the full menu or typing

help followed by a particular function name or M-file name. For example, help cos gives

help on the cosine function.

You can make a keyword search by using the lookfor command.

The number of digits displayed is not related to the accuracy. To change the format of

the display, type format short e for scientific notation with 5 decimal places, format long

e for scientific notation with 15 significant decimal places and format bank for placing

two significant digits to the right of the decimal.

The commands who and whos give the names of the variables that have been defined in

the workspace.

The command length(x) returns the length of a vector x and size(x) returns the

dimension of the matrix x.

When using MATLAB, you may wish to leave the program but save the vectors and

matrices you have defined. To save the file to the working directory, type save filename

where "filename" is a name of your choice. To retrieve the data later, type load filename.

Learning to work in M-Files M-files are macros of MATLAB commands that are stored as ordinary text files with the

extension "m", that is ‘filename.m’. An M-file can be either a function with input and output

variables or a list of commands.

Page 10: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 10

For example, consider using MATLAB on a PC with a user-defined M-file stored in a directory

called "C:\MATLAB\MFILES". Then to access that M-file, either change the working directory

by typing cd c:\matlab\mfiles from within the MATLAB command window or by adding the

directory to the path.

Permanent addition to the path is accomplished by editing the C:\MATLAB\matlabrc.m file,

while temporary modification to the path is accomplished by typing

path(path,'c:\matlab\mfiles') from within MATLAB.

Or, this can easily be achieved through the path browser. As example of an M-file that defines

a function, create a file in your working directory named yplusx.m that contains the

following commands: function z = yplusx(y,x) z = y + x;

The following commands typed from within MATLAB demonstrate how this M-file is used:

x = 2; y = 3; z = yplusx(y,x)

All variables used in a MATLAB function are local to that function only, whereas, variables

which are used in a script m-file which is not a function are all global variables.

Lab Task

1 Generate and plot the following signals in MATLAB using an M-File, each plot must

include proper axis labeled as well as the title. Also, display the last three plots using

subplot command.

I. x1(t)=sin(t)

II. x2(t)=sin(2t)

III. x3(t)=sin(3t)

IV. x4(t)=sin(4t)

V. x5(t)=x1(t)+x2(t)

VI. x6(t)=x5(t)+x3(t)

VII. x7(t)=x6(t)+x4(t)

VIII. y1(t)=x1(t+1)

IX. y2(t)=x2(3t)

X. y3(t)=x3(2t+1)

2 What are the purposes of the commands clear all; close all, clc, axis, title, xlabel, and

ylabel?

3 Construct a function in M-file by the name of greater(x,y), which will take two inputs from

the user, finds the value that is greater among the two and then displays it.

Page 11: LAB No. 2 Introduction to Matlab - Functions and Plotting · 2016. 11. 24. · p pentagram h hexagram For example, if we wanted to plot the graphs above as crosses in red, the command

Abasyn University Islamabad Campus | Digital Signal Processing – Lab Manual Page 11

4 Construct a function that computes a factorial of a number given to it. Use help to find the

command and how to use it, and then use it to get the answer.

5 Create an m-file that takes two vectors from user. Make sure that the second vector taken

is of the same size as the first vector (Hint: use while loop). In a while loop, generate a

third vector that contains the sum of the squares of corresponding entries of both the

vectors.

Checked By: Date: