ece 309 lecture 2 overviedvanalp/ece 450/ece_309_lect_2_fall_14_dept...script m-file example 2 •...

61
ECE 309 Lecture 2 Overview Script M-files New commands/functions: display, date, input Graphs New commands/functions: plot, xlabel, ylabel, title, grid, figure, stem, linspace, logspace, semilogx, semilogy, loglog, plotyy, subplot Visualizing Engineering Signals New commands/functions: stairs, strips, square, sawtooth, axis, repmat Logical Operators and Switches New functions: xor, all, any, find Function M-files Introduction to the Symbolic Toolbox New commands/functions: syms, simplify, expand, factor, solve, diff, int, ezplot, ezplot3, pretty Includes Exercise Sets 6 10 ECE 309 Intro. to MATLAB 1

Upload: others

Post on 30-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

ECE 309 Lecture 2 Overview

• Script M-files

– New commands/functions: display, date, input

• Graphs

– New commands/functions: plot, xlabel, ylabel, title, grid, figure, stem,

linspace, logspace, semilogx, semilogy, loglog, plotyy, subplot

• Visualizing Engineering Signals

– New commands/functions: stairs, strips, square, sawtooth, axis, repmat

• Logical Operators and Switches

– New functions: xor, all, any, find

• Function M-files

• Introduction to the Symbolic Toolbox

– New commands/functions: syms, simplify, expand, factor, solve, diff, int,

ezplot, ezplot3, pretty

• Includes Exercise Sets 6 – 10

ECE 309 Intro. to MATLAB 1

Page 2: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Script M-Files (Script files with extension .m)

• So far we have worked in the interactive mode, typing code in the

command window.

• We could also type our code in a script file (also called an M-file).

All the commands in the M-file will be executed when we type the

name of the M-file in the command window.

• To create an M-file, in the command window (in the HOME tab),

click on New (from the top menu bar, on the left). This brings up

the Editor tab & the Editor window, in which we will type our code.

• To name your M-file, from the Editor tab’s top menu, select Save

Save As and type in the name you would like to give to the M-

file. (Don’t include the .m part in the title.)

• When you type in the code, anything preceded by a percent sign

(%) will be treated as a comment, and will not be executed.

ECE 309 Intro. to MATLAB 2

Page 3: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Script M-File Example 1

• The following example is for an M-file that we will save as square_root.m. (The .m part is added by the Editor/Debugger.)

% Program square_root

% This program computes y = the square root of x, as x

% goes from 0 to 10, and creates a 2-column table, with % columns for x and y.

%

x = [0 : .1 : 10]; y = sqrt( x);

table = [x’ y’]

• To save the M-file, go to the top menu, and select Save. Then run the code by hitting the green arrow ( , again from the top menu).

• Alternate way to run the code: In the command window, type the name square_root after the prompt >>. The file should execute, and the resulting table will be displayed in the command window.

ECE 309 Intro. to MATLAB 3

Page 4: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Script M-File Example 2

• Suppose that we want to create an M-file that will generate a

header (containing the your name, the class, the assignment name,

and the date) to be used in all of your homework or exercise files.

• You will need three new functions:

– the display function, with syntax

disp(‘desired text‘)

which will display whatever text is written between the single quotes;

– The date function, with syntax

date

which will return the current date; and

– The input function, discussed in the next page. (Skip to next page.)

• First create and save an M-file with the title header_lastname

(Note: here lastname means your own last name.)

ECE 309 Intro. to MATLAB 4

Programs like this

are called “utilities.”

Page 5: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Receiving User Input

• The input function has syntax: value = input(‘prompt’)

– this displays a prompt for the user to provide some input,

and assigns the variable name value to that input.

This function would typically be used in an M-file, when user-

input is required.

• Example 1 (from the command window):

>> x = input('Enter desired value for variable x:’)

Enter desired value for variable x: 4

x =

4.0000

• Special case: If the desired input (from the user) is textual, an

additional argument (‘s’) follows the text to be displayed.

(Example follows.)ECE 309 Intro. to MATLAB 5

After this slide, return

to previous slide &

execute last bullet.

Page 6: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Script M-File, Example 2, continued

• In the editor window, type the following text:

% Program header_lastname

% Author: yourname Last Modified: currentdate

% This program is to be called in any homework sets or tests for ECE 309; it % will type my name, the course number, the assignment name, and the date, % with a trailing blank line. (It will request the name of the assignment as a user % input.)

format compact % eliminates extra vertical spacing

disp (‘yourname’), disp (‘ECE 309’),

assignment_name = input(‘Type the name of the assignment here:’, ‘s’)

date, disp (‘ ‘)

After again saving the file with the name header_lastname, return to the command window, and type >> header_lastname. Fill in anything you want for the “Assignment Name.”

Note: use header_lastname as the first executable line of any MATLAB exams or assignments to be submitted for this course.

ECE 309 Intro. to MATLAB 6

Make your name

display last name

first in the code.

Note the ‘s’, since the user

will input a string variable.

Page 7: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 6

1. Write a script M-file* named trig_examples to

a. calculate y = sin2(x), for x values: [0 30 60 90];

b. calculate z = cos2(x), for the x values given in a;

c. display x, y and z as 3 columns, as in a table. (No headings or

column labels are required, and no special formatting is required.

Hint: See Lecture 1, p. 45, or Lecture 2, p. 3)

2a. Write a script M-file, called my_data, that defines coefficient matrix

A and b for the system of equations (of the form Ax = b) given below.

2x1 – 3x2 + x3 – x4 = 5

x1 + x2 + x4 = 7

-x1 + 2x2 + 4x3 = 1

8x1 – x2 = 5

ECE 309 Intro. to MATLAB 7

* Remember to use header_lastname as the first executable line of

code in any of your script M-files that will be collected.

Script M-files are often

used to define data.

Page 8: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 6

2b. Write another script M-file, called sys_solve, that will solve the

system of equations Ax = b as defined in part a, for the unknown vector

x. The first executable line of code in your program after the header line

will be:

my_data % defines coeff matrix A and constant vec b

so that the coefficient matrix A and constant vector b for your system

will be defined. You should only need one more line of executable code

now to solve for x. (Hint: See Lecture 1, p. 45.)

Note that you are running one script M-file (my_data) inside of another

(sys_solve) for this problem.

3. Save the script my_data (from problem 2a) with a new name,

my_data_new. Modify the new script, leaving the coefficient matrix A

unchanged, but allowing the user to input any four components for the

vector b. Then modify sys_solve to call my_data_new (instead of

my_data) and use it to solve the system when b = [1 0 2 0]’.

ECE 309 Intro. to MATLAB 8

Page 9: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Introduction to Graphs

• To graph the function s(t) = cos(8pt), for t [0, 1], we choose a

spacing of .025 for the time points, and the session becomes

>> t = [ 0 : .025 : 1 ];

>> s = cos(8*pi*t);

>> plot (t, s), xlabel (‘t’), ylabel (‘cos(8 pi t)’)

• The plot will appear in a graphics window.

• To print out the graph, select (in the graphics window) File Menu

Print

• To add a title to a plot, use the function title, typing the desired title

in single quotes inside parentheses. (Example follows)

• To add text to the plot itself, use the insert menu in the graphics

window. (This will also work for axis labels and graph titles. Demo

follows.)

ECE 309 Intro. to MATLAB 9

Don’t print now.

Page 10: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Graphs, cont.

• We can also graph several curves on a single plot (overlay plots).

• We can use a different line type to distinguish the curves.

• Example: say we want to plot s(t) = cos(8pt) and r(t) = sin(4pt) on a single plot, for t [0, 1] with spacing .025, and a dotted line for the function r(t).

>> t = [0 : .025 : 1]; % you don’t need to re-type this line

>> s = cos(8*pi*t); r = sin(4*pi*t);

>> plot (t, s, t, r, ‘- -’), xlabel (‘t, seconds’)

>> grid, title(‘r(t) and s(t)’)

• Note: the grid command in the last line of code added a grid to the graph.

• The plot will appear in a graphics window. Use the Insert menu (text) to label one of the curves “s, volts”, and the other “r, volts”.

ECE 309 Intro. to MATLAB 10

Page 11: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Graphs, cont. - Refinements -

• We can change the line color, the plot symbols, and line type (solid, dotted, or dashed), in graphs, using a character string (set off with single quotes) made from one entry from any or all of the sets below:

Colors: {y (yellow), m (magenta), c (cyan), r (red), g (green),

b (blue), w (white), k (black) }

Plot symbols: { . , o, x , + , * , s (square), d (diamond), v (triangle) }

Line types: { - (solid), : (dotted), -- (dashed) }

• Example: Plotting s(t) from the previous page, with a red dashedline, using diamonds for plot symbols (to mark the data points):

>> plot( t , s , ‘r d - -’)

ECE 309 Intro. to MATLAB 11

Page 12: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Graphs, continued - More Practice

• Example: To graph x(t) = t2, for t [0, 3], using blue circles to make the data points, and connecting the points with a dotted red line, try graphing x(t) once for the line and once for the data points:

>> t = [ 0 : .2 : 3]; x = t .^ 2;

>> plot(t, x, ‘bo’, t, x, ‘r : ’)

• Use the Insert menu in the graph window to add axes labels and a title.

• Example: To graph x(t) = t2 and y(t) = 2t in two separate windows, we type the following:

>> t = [ 0 : .2 : 3]; x = t .^ 2; y = 2*t;

>> plot(t, x), figure, plot(t, y)

• Note that the figure command creates a new window for the second plot; without it, the second plot would overwrite the first plot.

ECE 309 Intro. to MATLAB 12

Page 13: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using the PLOT Tab

• Recall (from Lecture 1) that the MATLAB desktop shows 3 tabs

(HOME, PLOTS, APPS) available near the top. Suppose now that

we have created (in the HOME tab) 2 vectors to be plotted – say t

and x(t) from the previous page.

• Now we will switch from the HOME tab to the PLOTS tab; in the

Workspace window, we select the two vectors (t and x) with the

mouse; then we click on the Plot icon:

to create a standard plot. (The plot will appear in a Figure window,

just as if we had typed: >> plot(t, x).)

• Once the plot appears, we can use the Insert menu, as before, to

insert the title, axes labels, a grid, desired text, etc.

• If we wanted the plot to show data points not connected with a line,

we would have selected the Scatter icon instead of the Plot icon.

ECE 309 Intro. to MATLAB 13

Page 14: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Graphing Discrete Data

• To graph discrete data (as for ECE 351), use the command steminstead of plot.

– Modifications for color work the same as they do in the plot command;

– Titles, axis labels and grids can be added as for the plot command.

• Example: To graph x(n) = 2n + 4 for n [0, 1, …, 10], in red, type :

>> n = [ 0 : 10]; x = 2*n+4;

>> stem(n, x, ‘r ’)

>> xlabel(‘n’), title(‘Practice Graph’), grid

• To fill in the red circles, use the additional modifier: ‘fill’

>> stem(n, x, ‘r’, ‘fill’)

ECE 309 Intro. to MATLAB 14

Page 15: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

ECE 309 Intro. to MATLAB 15

Two More Ways to Generate Vectors

• Another way to fill a vector with equally spaced numbers is to use

the function linspace, requiring 3 arguments, with syntax:

linspace(1st_value, last_value, # of values)

– Example: To get 20 linearly-spaced numbers between 0 and 2p,

type:

>> t = linspace(0, 2*pi, 20)

• To get a vector of numbers with logarithmic spacing, ranging from

10^a to 10^b, use the function logspace, requiring 3 arguments,

with syntax:

>> logspace(a, b, # of values)

– Example: To get an array starting at 100 = 1, ending at 103 =

1000, with 20 points, type:

>> t = logspace(0, 3, 20)

Example follows.

Example follows.

Page 16: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Generating Vectors: Linspace (Bad) Example

• Bad example for linearly-spaced points, and a sinusoidal plot:

>> t = linspace(0, 2*pi, 20); s = sin(2*pi*t); plot(t, s)

>> title('sin(2*pi*t)'), xlabel('t')

ECE 309 Intro. to MATLAB 16

0 1 2 3 4 5 6 7-1

0

1sin(2*pi*t)

t

Note for students who have

had ECE 350 and/or ECE 351:

We took 20 samples in about 6

seconds (2*pi), for a sampling

rate of about 3 samples/sec.,

exceeding the required Nyquist

Rate.

But the plot does not look much

like a sinusoid!

Moral: Sampling at the Nyquist rate

guarantees that the signal (ideally)

can be recovered perfectly with a

LPF. It doesn’t mean the plot formed

by connecting the sampled points

with straight lines will look right.

Page 17: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Generating Vectors: Linspace (Good) Example

• For linearly-spaced points, and a sinusoidal plot:

>> t = linspace(0, 2*pi, 100); s = sin(2*pi*t); plot(t, s)

>> title('sin(2*pi*t)'), xlabel('t')

Always be sure that the graph you generate in MATLAB looks

correct, based on your own knowledge of math.

Try to get maximum resolution by scaling the axes to fit the data.

Another way to do this: >> help axis (see “tight” option)

ECE 309 Intro. to MATLAB 17

0 1 2 3 4 5 6-1

0

1sin(2*pi*t)

t

In graph window:

use “Edit Axis

Properties” to

change range of x

axis to 0:6.28.

Page 18: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Logarithmic Plots

• For logarithmically-spaced points, it often makes more sense to

graph them on a log-scale.

– Log scales also often make sense when the range of values is

very large.

• To make just the x-axis logarithmic, we use the syntax:

• semilogx(x, y) (behaves like the plot(x, y) command)

• To make just the y-axis logarithmic, we use the syntax:

• semilogy(x, y) (behaves like the plot(x, y) command)

• To make both axes logarithmic, we use the syntax:

• loglog(x, y) (behaves like the plot(x, y) command)

ECE 309 Intro. to MATLAB 18

Examples follow.

Page 19: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Logarithmic Plots

• For logarithmically-spaced points, and an exponential plot, compare

the two figures generated below :

>> t = logspace(0, 3, 8); s = exp(-.02*t);

>> plot(t,s, '+-'), xlabel('t'), title('plain plot')

>> figure, semilogx(t, s, '+-'), xlabel('t'), title('log scale on t axis')

ECE 309 Intro. to MATLAB 19

100

101

102

103

0

0.2

0.4

0.6

0.8

1

t

log scale on horiz. axis

0 100 200 300 400 500 600 700 800 900 10000

0.2

0.4

0.6

0.8

1

t

plain plot

Many pts. scrunched

into small space

Pts evenly

spaced

on t-axis.

Poor

resolution

Page 20: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Logarithmic Plots

• For logarithmically-spaced points, and an exponential plot, consider

the figure generated below :

>> t = logspace(0, 3, 8); s = exp(-.02*t);

>> loglog(t,s, '+-'), xlabel('t'), title('loglog scale’)')

ECE 309 Intro. to MATLAB 20

100

101

102

103

10-10

10-8

10-6

10-4

10-2

100

t

loglog scale

Pts evenly spaced

on t-axis; better

resolution for small

s values.

Page 21: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Overlaying Curves with Data of Widely Different

Range of Values or Different Units (thus requiring two different y-axes: command plotyy)

• The command plotyy allows for plotting one set of points (x1, y1)

with the y-axis on the left side, and another set of points (x2, y2)

with the y-axis on the right side. Syntax: plotyy(x1, y1, x2, y2)

• Example:

>> t = [0 : .1 : 20];

>> y1 = sin(pi*t/2); % range: -1, 1

>> y2 = 10 * sin(pi*t/2) .* exp(-.1*t); % range ~: -10, 10

>> plotyy(t, y1, t, y2)

• Using different scales on the y-axes allows you to show greater

resolution for the y1 set.

ECE 309 Intro. to MATLAB 21

Page 22: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Showing Several Plots on a Page, in Different

Sub-Windows or Panes – The Subplot Command

ECE 309 Intro. to MATLAB 22

Pane 1 Pane 4

Pane 2 Pane 5

Pane 3 Pane 6

Example for 6 plots, in 3

rows, 2 columns: (3, 2)

• Suppose that we would like to show

several graphs, all on one page.

• If the number of graphs to be plotted

is m x n, we can arrange the plots in

an array with m rows and n columns

• Panes are numbered by reading

down the columns. To fill the jth pane

with the plot of (x, y), we use

the commands:

subplot(m, n, j), plot(x, y)

• Note: titles and axes labels

should be added as usual,

right after each plot

command.

Example: (2 plots, 1 under the other)

>> x = 1:10; % note: no brackets!

>> y1 = 2*x-3; y2 = log10(x);

>> subplot(2, 1, 1), plot(x, y1)

>> subplot(2, 1, 2), plot(x, y2)

Page 23: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 7 - Note: You may use whatever MATLAB technique you

prefer to generate these graphs. Create a single M-file containing the required

code for these problems. Always: use enough points so that the curves are

smooth, and suppress the echo for the vectors. You will be asked to submit only

the M-file and the plots.

1. Generate a plot for the decaying exponential:

s(t) = sin(4pt) exp(-t), for t values from 0 to 1 sec.

Include axes labels and a title for the plot, and a grid.

2. Plot y(t) = t3 and z(t) = , for 0 t 2, on a single graph with a grid.

Label both curves and the horizontal axis, and include a title for the

plot. Make the plot for z a dashed line, and the plot for y a solid line.

3. Plot s(t) = et/2, and w(t) = sin(2pt), for 0 t p, one underneath the

other on a single page, labeling both axes for each plot. Use circles

for the data points for s, with no line connecting the points. Use

triangles for the data points for w, with a solid line connecting the

points.ECE 309 Intro. to MATLAB 23

3 t

Page 24: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 7, continued

4. Recall that the x and y coordinates for a point on a circle of radius r,

at angle q, are: x = r cos(q), y = r sin(q). To plot a circle of radius 5:

a. Create a vector containing 100 q-values, linearly spaced

between 0 and 2p.

b. Create a vector of corresponding x values (one for each value of q)

and another vector of corresponding y values (one for each value

of q), assuming that the radius of the circle is 5.

d. Generate a plot of (x, y) values. After your plot command, insert

the command: >> axis(‘equal’) to make the scaling on the x and

y axes identical (to avoid distortion of the circle).

e. Include appropriate labels for the x and y axis, as well as a title for

the graph.

5. Plot the function y = 10x, for x values ranging from 0 to 4, using a

linear scale on the x-axis and a log scale on the y-axis. Label the x

and y axes, and include a title and a grid.ECE 309 Intro. to MATLAB 24

Page 25: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 7, continued

6. Generate a vector x containing 20 points, logarithmically spaced,

between 1 and 10,000. Plot y = ln(x), using a log scale on both the x

and y axes. Label the x and y axes, and include a title and a grid.

7a. For integer values of n ranging from 0 to 8, plot the discrete data

set: x[n] = ln(n). Label both axes and include a plot title and a grid.

7b. Generate another plot for the data given in 7a, with the data circles

filled in. Label both axes and include a plot title and a grid.

8. Recall that the RC filter has transfer function: H(f) = . For

frequency values ranging from f = -200 KHz to 200 KHz, with R = 10

KW and C = 1 mF, plot the magnitude and phase for the transfer

function, on one plot, with the left vertical axis showing |H(f)|, and the

right vertical axis showing the phase angle, in radians. Label the

horizontal axis, and use Insert Textbox to add a label for each curve.

ECE 309 Intro. to MATLAB 25

fRC2j1

1

p

Hint – review MATLAB func-

tions: abs, angle and plotyy.

Page 26: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Visualizing Engineering Signals

(Example: same data, different views)

• Enter: >> t = [.1 .2 .3 .4 .5];

>> x = [1 8 4.5 9.6 3];

• Try: >> plot(t, x), figure

>> stem(t, x), figure

>> stairs(t, x)

0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.50

5

10

0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.50

5

10

0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.50

5

10plot stem stairs

Good for sample

& hold, step

functions, etc.

26ECE 309 Intro. to MATLAB

Page 27: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Strip PlotsFor syntax, type: >> help strips

• ECE 460 Example: Say we want to plot the FM waveform:

x(t) = sin(2p f(t) * t)

where f(t) = 250 + 240*sin(2*pi*t), the message.

• Let’s plot several strips, stacked horizontally, where each strip contains .25 seconds of data; we will do a total of 2 seconds (thus, 8 strips):

• MATLAB Code:

>> fs = 1000; ts = 1/fs % sample freq 1000 samples/sec

>> t = 0 : ts : 2; % 2 sec. of time values

>> f = 250 + 240* sin(2*pi*t); % the message

>> x = sin(2*pi*f .*t) % the FM waveform (2 sec. worth)

>> strips(x, .25, fs) % strip plot, each strip = .25 sec. worth

27ECE 309 Intro. to MATLAB

Page 28: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Strip Plot Result from Previous Example:

FM Waveform

0 0.05 0.1 0.15 0.2 0.25

1.75

1.5

1.25

1

0.75

0.5

0.25

0

28ECE 309 Intro. to MATLAB

Page 29: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Periodic Functions: Sinusoidal(Reviewing: sinusoids are the model for several periodic functions.)

>> t = linspace(0, 1, 101);

>> A = 5; % amplitude

>> f = 2; % freq in Hz = cycles/sec.

>> ph = pi/8; % phase in radians

>> sinewave = A*sin(2*pi*f*t + ph);

>> plot(t, sinewave)

0 0.2 0.4 0.6 0.8 1-5

0

5

29ECE 309 Intro. to MATLAB

Page 30: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Periodic Functions: Square Waves• Syntax: square(2*pi*f*t, d)

– where f is frequency: cycles/sec. (mimicking sinusoidal notation)

– and where d is duty cycle (50% by default)

• Example: >> t = linspace(0, 1, 101);

>> sqw = square(2*pi*4*t, 75) % freq. 4 cycles/sec., 75%

% duty cycle

>> plot(t, sqw)

>> axis([0 1 -1.2 1.2]) % scaling the axes

0 0.2 0.4 0.6 0.8 1

-1

-0.5

0

0.5

1

To get ampl. levels {0, 1}

instead of {1, -1}, try:

>> sqw2 = (sqw+1)/2;

>> plot(t, sqw2)

30

>> help axis

ECE 309 Intro. to MATLAB

Page 31: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Periodic Functions: Sawtooth

• Syntax: sawtooth(2*pi*f*t, frac_pk)

– where f is frequency: cycles/sec. (mimicking sinusoidal notation)

– and where frac_pk is the fractional location of the sawtooth peak

• Example 1: Generate a sawtooth with 3 Hz = 3 cycles/sec, and a peak at the end of a cycle (which is the default: frac_pk = 1, unspecified).

>> t = linspace(0, 1, 101);

>> saw1 = sawtooth(2*pi*3*t) % peak at end of cycle

>> plot(t, saw1)

Now generate a 3 Hz sawtooth with the peak half-way through the cycle:

>> saw2 = sawtooth(2*pi*3*t, 1/2)

>> plot(t, saw2)

31ECE 309 Intro. to MATLAB

Page 32: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using the repmat Function[Ref: MATLAB Help]

repmat: Replicate and tile an array or matrix

B = repmat(A, M, N) creates a large matrix B consisting of an M-by-N

tiling of copies of some matrix A.

General Example: For M = 2 and N = 3, we would have:

Specific Example 1: If A = [1 2 3], B = repmat(A, 2, 3), yields:

B =

Specific Example 2: If A = [1 2 3], then B = repmat(A, 1, 3) yields

B = [1 2 3 1 2 3 1 2 3] 32

AAA

AAA where A is itself the matrix

we are trying to replicate.

321321321

321321321

ECE 309 Intro. to MATLAB

Page 33: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Discrete Periodic Sequences : Square Waves

(getting 5 repetitions of: 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)

Strategy: Use repmat to repeat the discrete sequence as a “1-row, 5-

column” repetition.

First we build the “block” to be repeated:

>> x1 = ones(1, 4); x2 = zeros(1, 6); x = [x1 x2]

Set # of times to be repeated: >> N = 5;

>> xr = repmat(x, 1, N); % to get 1 x 5 tiling of above pattern

>> n = 0:length(xr) - 1; stem(n, xr);

330 5 10 15 20 25 30 35 40 45 50

0

0.2

0.4

0.6

0.8

1

ECE 309

Page 34: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

ECE 309 Intro. to MATLAB 34

Logical & Comparison Operations

(to get answers for true/false questions: T = 1, F = 0)

Operator Description Example

< Less than: returns a 1 for values < RHS A < 1 = [ 1 0 0]

< = Less than or equal to A <= 1 = [ 1 1 0]

> Greater than: returns a 1 for values > RHS B > 2 = [ 1 0 0]

> = Greater than or equal to A >= B = [0 0 1]

= = Equal to: returns a 1 for values : LHS = RHS A = = B = [0 0 0]

~ = Not equal to A ~ = B = [1 1 1]

& Logical And (A<1) & (B>2) = [1 0 0]

| Logical Or (A 1) | (B>2) = [1 1 0]

~ Logical Not ~(A>B) = [1 1 0]

For examples, assume: A = [ 0 1 2 ]; B = [ 3 2 1 ];

LHS: left-hand side; RHS: right-hand side

Page 35: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

More Logical Functions/Operators

• xor: exclusive or

• all returns true (= 1) if all elements of a vector meet the condition

of the argument

– e.g., all(x < 0) will return 1 if every element of x is negative.

• any returns true (= 1) if any element of a vector meets the

condition of the argument

– e.g., any(x < 0) will return 1 if any element of x is negative.

• find returns the indices of any elements of a matrix that meet the

condition of the argument

– e.g., [r c] = find(A < 0) will return row and column indices

of negative elements of A

ECE 309 Intro. to MATLAB 35

Page 36: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using Logical Switches

to Turn Signals On and Off• Example: Say we want to generate the signal:

sin(2*pi*130*t) 0 < t < 1

sin(2*pi*220*t) 1 ≤ t < 2

sin(2*pi*300*t) 2 ≤ t < 3

• Approach: Make a time base vector, say t for values in (0, 3), then make logical switches to turn on the various signal components:

sw1 = (t < 1) to turn on the 130 Hz sinusoid

sw2 = (t >= 1) & (t < 2) to turn on the 220 Hz sinusoid

sw3 = (t >= 2) to turn on the 300 Hz sinusoid

MATLAB Code:

>> fs = 8192; ts = 1/fs; t = 0 : ts : 3;

>> sw1 = (t<1); sw2 = (t >=1) & (t < 2); sw3 = (t >=2)

>> x = sw1 .* sin(2*pi*130*t) + sw2 .* sin(2*pi*220*t) ...

+ sw3 .* sin(2*pi*300*t);

>> plot(t, x)

x(t) =

Use fs = 8192

samples/sec.

36Intro. to MATLAB

Page 37: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 8 - Create a single M-file for these problems; for

graphing problems, suppress the echo for all vectors, label the axes,

and include a title.

1. Generate a plot for the signal that is the output of a sample-and-hold circuit,

if the samples values: {1, 2.6, 3.4, 5, 8} were taken at fs = ½ sample/sec.,

starting at t = 0 sec.

2. Use a strip plot to generate 4 seconds worth of data (starting at t = 0), where

each “strip” is .5 seconds worth of data, for the AM signal:

s(t) { cos(2p100t) + 2}

if s(t) is the message signal: s(t) = sin(10pt).

3a. Plot 4 cycles of the square wave with amplitude levels {+2, -2}, period T = 2

sec., and duty cycle 25% (for the “high” value). (Choose a reasonable value

for fs.)

3b. Repeat problem 3a, but change the amplitude levels to {0, 2}.

4. Plot 5 cycles of a triangular (sawtooth) wave, where the peak is at the end of

the cycle, and the period is T = .2 sec. (Choose a reasonable value for fs.)

37ECE 309 Intro. to MATLAB

Page 38: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 8, continued

5. Use MATLAB’s repmat function to plot a discrete sequence with 6

repetitions of: {0, 1, 2, 3, 4}, starting at n = 0.

6. Use logical switches to plot the function shown below:

7. Consider the matrix pascal(6). Make a 2-column table showing the

row and column for all entries in this matrix that are greater than 50.

Hint: Type: >> help pascal, and >> help find.38

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2-1

-0.5

0

0.5

1

sin(6pi t)

ECE 309 Intro. to MATLAB

Page 39: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 8, continued

8. Use MATLAB’s stairs function to generate the plot below. (If you

have had ECE 350, you may recognize this as the window:

u(t) – u(t – 3).) Use the same scales for the axes as shown.

39

-2 -1 0 1 2 3 4 5-0.5

0

0.5

1

1.5

t

ECE 309 Intro. to MATLAB

Page 40: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Function M-files

• So far, we have written script M-files.

• Think of these as mostly programs that you probably will

just use once (exception: header_lastname);

• Sometimes, we would like to re-use an M-file, and change

some of the variables from one run to another.

• In this case, we usually would want a function M-file

rather than a script M-file.

• We pass in the values of the input variables (as arguments

of the function) when we call the function from the

command window.

• Note: that this is the same as in math: functions have

arguments.

ECE 309 Intro. to MATLAB 40

Page 41: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Function M-files

• Functions are just a special type of M-file or script.

• The first word must be: function

• The first line is of the form: function [output_parameter_list]

= function_name(input_parameter_list)

• After the first word (function), put the (optional) output parameters

inside square brackets [ ]. (Omit the square brackets and “=“ sign if

there are no output parameters.) The square brackets can also be

omitted if there is only one output parameter.

• The function_name is what we will use to call the function from the

command window. It must be the same as the file name (without the

“.m”).

• After the file name is the (optional) input_parameter_list.

ECE 309 Intro. to MATLAB 41

Page 42: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

User-Defined Functions : Function M-files

• Good Practice: Don’t alter any of the input parameters with the

code in your function.

• The input and output variables can be of any type: scalars,

vectors, matrices, or strings.

• Example: to create the function M-file titled: farh2cels (converting

degrees Fahrenheit to degrees Celsius)

– From the HOME tab, use the New pull-down menu (top left)

and select Function to open the Editor tab & window.

ECE 309 Intro. to MATLAB 42

function [ output_args ] = Untitled( input_args )

% Summary of this function goes here

% Detailed explanation goes here

end

MATLAB will

generate the

template

shown here.Save as: fahr2cels

Page 43: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

User-Defined Functions : Function M-files

function temp_cels = fahr2cels(temp_fahr)

% farh2cels converts temperature from degrees F to degrees C.

% This function converts the input argument (temp. in degrees

% Fahrenheit) to output argument (temp. in degrees Celsius.)

temp_cels = (5/9)*(temp_fahr - 32);

end

From the command window, to convert 100F to C, type:

>> fahr2cels(100)

ans =

37.7778

Example converting a vector containing several temperatures in F :

>> X = [32 70 100]; Y = fahr2cels(X)

Y = 0 21.1111 37.7778

ECE 309 Intro. to MATLAB 43

Type in the code.

Page 44: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Review - Script M-files vs. Function M-files

Script M-files

• script for something you plan to do

once, not repeatedly; e.g., a HW

Assignment

• execute the commands by typing

the name of the script in the

command window or hitting the run

arrow

• variables used in the script become

part of the workspace

Function M-files

• script to define a function that you

plan to re-use multiple times, with

different input arguments

• variables used in the function are

(generally) local to the function,

unless passed through the

input/output parameter lists or

declared “global”

ECE 309 Intro. to MATLAB 44

Both are file types that

• end with the extension .m

• contain MATLAB commands that could be executed from the

command window

• are created (usually) in the editor window

Page 45: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Another Function M-file Example

• Now we will create a function to find the sum of a geometric series.

The name of the function will be: geo_series.

• Recall that a finite geometric series is of the form:

a + ar + ar2 + ar3 + … + arN-1

where a is the first term in the series, r is the “common ratio”, and

N is the number of terms.

and the sum is given by S =

• In-class example: 1 + ½ + ¼ + … + 1/128 = __________

• For the function M-file, the input arguments will be: ___________

and the output arguments will be: the sum, called sum

ECE 309 Intro. to MATLAB 45

r1

ara N

Page 46: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Function M-file Example: Geometric Series Sum

• From the HOME tab, select New Function to generate the

template for a new function in the editor window:

• Modify the above template, changing:

– Untitled2 geo_series (the name of our function)

– input_args a, r, N

– output_args sum

– In class (together), put in the equation for the output variable (right

before the end statement), fill in some comments, and check your

code with at least 2 examples using a small value for N.

ECE 309 Intro. to MATLAB 46

function [ output_args ] = Untitled2( input_args )

%UNTITLED2 Summary of this function goes here

% Detailed explanation goes here

end Save as: geo_series

Include header file!

Page 47: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 9

1. Write a function M-file called par_res that

– takes as input two resistor values (say R1 and R2), and

– outputs the equivalent resistance, say R_eq, if the two resistors are in

parallel.

2. Write a function M-file called circle_area that

– takes as input the radius of the circle, say radius; and

– yields as output the area of the circle, say area.

3a. Write a function M-file called triangles that

– takes as input 3 sides (say a, b and c) of a triangle;

– yields the perimeter, say p, and area, say A (using Heron’s formula given

below) of the triangle as output.

Perimeter: p = a + b + c;

Heron’s formula for Area: A = sqrt(s(s-a)(s-b)(s-c)),

where s = p/2, the semi-perimeter

ECE 309 Intro. to MATLAB 47

Remember: the first executable line of code

in each script M-file is: header_lastname.

Cont.’ on next page.

Page 48: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 9, continued

3b. Use the command window to check that your code works for a 3-4-5 right

triangle and a 5-12-13 right triangle. (Use A = ½ bh in your check for the

area.) Note that the check does not have to be part of the function M-file.

4. (previous exam problem) From physics, the capacitance (in F) between 2

parallel plates, filled with a dielectric material of relative permittivity e, can

be approximated by the equation: C e0 e A/d, where A is the area of the

plates (in sq. m), d is the distance (in m) between the plates, and e0 is the

electric constant, 8.854×10−12 F/m.

a. Write a function M-file to find the capacitance between two rectangular

parallel plates,

• with inputs: the length and width of the plates (both in m), the permittivity of

the dielectric material separating the plates, and the distance between the

plates (in m); and

• with output: the capacitance between the two plates (in F).

ECE 309 Intro. to MATLAB 48

Page 49: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 9, continued

b. After debugging your code, use your program to find:

the capacitance between parallel rectangular plates of length 3 mm and

width 4 mm, separated by distance d = 0.2 mm, if the relative permittivity of

the material between the plates is 2.5. (Be careful with the units.)

5. Legend: When the inventor of the game of chess showed the game to his

king, the king offered him whatever prize he desired. The inventor said:

I won’t be greedy. Just give me one grain of rice for the first square, two

grains for the second square, four grains for the third square, etc., doubling

the number of grains for each square, up to the last square on the board.

Write a MATLAB M-file called chess_board to determine how many grains

of rice the inventor would receive, in total.

ECE 309 Intro. to MATLAB 49

Hint: Note the type of series. You

may want to call one of the function

M-files already written.

Page 50: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

The Symbolic Toolbox

• MATLAB is designed to do vectorized numerical calculations.

• Without the Symbolic Toolbox, it wouldn’t be able to do things

like:

– Expand the product (x+4)5

– Find the anti-derivative of sinh(x)

– Simplify (sin2(x) + cos2(x))

• With the Symbolic Toolbox, we can do all of the above closed-

form calculations, and much more, using portions of a program

called Maple.

ECE 309 Intro. to MATLAB 50

Page 51: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Symbolic Toolbox – Some Examples

• First create symbolic variables:

>> syms x y a t % defines these as symbolic variables

• New symbolic variables can be defined as functions of those

already defined:

>> r = sin(x)^2 + cos(x)^2

>> g = atan(y/x)

>> h = (x + y)^4

• Expressions can be simplified and/or expanded:

>> r = simplify(r) % returns: r = 1

>> expand(h) % ans : x^4 + 4*x^3*y + …+ 4*x*y^3 + y^4

ECE 309 Intro. to MATLAB 51

New variables r, g &

h will be symbolic

automatically.

Page 52: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Symbolic Toolbox – More Examples

• We can factor expressions:

>> syms z; factor(z^3 + z^2 - 8*z - 12)

ans =

(z - 3)*(z + 2)^2

• We can solve (non-linear equations), say e5x = 2y

>> syms x y

>> eq = 'exp(5*x) = 2*y‘ % input equation as string variable

eq =

exp(5*x) = 2*y

>> [x] = solve(eq, x)

x =

log(2*y)/5

ECE 309 Intro. to MATLAB 52

Page 53: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

More on the Symbolic Function: Solve

[Ref: MATLAB help]

solve: Symbolic solution of algebraic equations.

solve(eqn1,eqn2,...,eqnN)

solve(eqn1,eqn2,...,eqnN,var1,var2,...,varN)

The eqns are (usually) symbolic expressions or strings specifying

equations.

The vars are symbolic variables or strings specifying the unknown

variables.

MATLAB’s solve seeks solutions to the equations.

If no analytical solution is found and the number of equations

equals the number of dependent variables, a numeric solution is

attempted.

ECE 309 Intro. to MATLAB 53

Page 54: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

More on the Symbolic Function: Solve

In Example 1 below, we will solve two (linear) equations with

symbolic coefficients & constants. Note: the equations in the system

do not have to be linear (as seen in Example 2 below):

Example 1: System to be solved for x and y: ax + by = p

cx + dy = q

MATLAB Code:

>> syms a b c d p q

>> [x, y] = solve('a*x+b*y = p', 'c*x + d*y = q', 'x', ‘y')

Example 2: A non-linear system: x2 + y = 10

x - y = 2

MATLAB Code:

>> [x , y] = solve('x^2 + y = 10', ‘x – y = 2')

ECE 309 Intro. to MATLAB 54

Page 55: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Symbolic (Closed-form) Differentiation & Integration;

First declare a, x, and y symbolic

Use diff(…) to find the derivative of the argument

>> diff(x^4) % performs d/dx; ans: 4 x^3

>> diff(x^3 + y*x, y) % performs d/dy, due to 2nd argument

>> diff(x^3, 2) % performs d2/dx2, due to 2nd argument

>> diff(x^3 + y*x) % ans: 3x^2 + y (default: d/dx)

Note: derivative was taken “dx” since no 2nd argument was given

Use int(…) to find the anti-derivative of the argument

>> int(x^4) % ans: x^5/5

>> int(a^x) % ans : a^x/log(a) (integrated dx)

Note: as with diff, 2nd argument can specify the variable of

integration

ECE 309 Intro. to MATLAB 55

Page 56: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Symbolic Integration over an Interval[Ref: MATLAB Help]

int(S, a, b) or int(S, [a, b]) or int(S, [a b]) is the definite integral of S

with respect to its symbolic variable from a to b. (Note: a and b are each

double or symbolic scalars.

int(S, v, a, b) or int(S, v, [a, b]) or int(S, v, [a b]) is the definite integral

of S with respect to v from a to b.

Example: To find a) and b) , type:

>> syms x

>> sol_a = int(x^2*cos(x), [0, pi])

>> sol_b = int(exp((-x^2)/2), [0, inf])

>> pretty(sol_b)

Note: the pretty function rewrites math expressions as they would

appear with standard typesetting (thus making them easier to read).

ECE 309 Intro. to MATLAB 56

dx)xcos(x0

2p

dxe0

2/x2

Page 57: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using Ezplot

• Ezplot is a user-friendly plotter (part of Symbolic Toolbox)

• Syntax: >> ezplot(fun) or >> ezplot(fun, [min, max])

• Example: >> ezplot('x^2/4 + y^2/8 = 1')

ECE 309 Intro. to MATLAB 57

-6 -4 -2 0 2 4 6-6

-4

-2

0

2

4

6

x

y

x2/4 + y

2/8 = 1

for x-axis

Page 58: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using Ezplot, continued

>> ezplot('1/(5*sin(x)-3)')

% using single quotes to define a string variable for the equation

% note: default domain: x = -2p : 2p

ECE 309 Intro. to MATLAB 58

-6 -4 -2 0 2 4 6

-1.5

-1

-0.5

0

0.5

1

1.5

2

x

1/(5 sin(x) - 3)

Page 59: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Using Ezplot3

• For a 3-D Parametric Plot, first: declare t symbolic. Then

• >> ezplot3('cos(t)', 'sin(t)', t, [-12 12])

ECE 309 Intro. to MATLAB 59

-1-0.5

00.5

1

-1-0.5

00.5

1-20

-10

0

10

20

x

x = cos(t), y = sin(t), z = t

y

z

Page 60: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 10

Write a single M-file for these problems, which are to be solved using

the symbolic toolbox. Use the disp function to display a problem

number before the output for each problem.

1a. expand: (3x2 + 4)4

1b. simplify: (x2 – 9)/(x+3)

1c. differentiate: tan2(x)

1d. differentiate with respect to y: cos2(x + 3y)

1e. find the anti-derivative of the hyperbolic sine: sinh(x)

1f. factor: x4 – 12x3 + 49x2 – 78x + 40

2. Solve the two non-linear systems of equations:

a. b.

ECE 309 Intro. to MATLAB 60

0y3x5

05y2x 2

1yx

0yx2

22

Page 61: ECE 309 Lecture 2 Overviedvanalp/ECE 450/ece_309_lect_2_fall_14_dept...Script M-File Example 2 • Suppose that we want to create an M-file that will generate a header (containing

Exercise Set 10

3. Solve the equation for x: e4x = 10y

4. Use MATLAB to find the closed-form solutions:

a. b. c.

d.

4. Use ezplot to generate a graph of :

a. f(x) = e-.2x cos(x), for x values ranging from 0 to 2p.

b. the hyperbola,

from x = -10 to 10.

ECE 309 Intro. to MATLAB 61

dxe0

2/x2

dx)xsin(e xp

p

dx

9)x(tan

12/

02

p

dx)x1(

1y

02

p

2y4

x 22