- 192 Views
- Uploaded on

Download Presentation
## PowerPoint Slideshow about 'MATLAB WORKSHOP' - carmela

**An Image/Link below is provided (as is) to download presentation**

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

MATLAB WORKSHOP

Lecture # 1

Monday August 26

- Introduction
- MATLAB Demos
- MATLAB Basics

Lecture # 2

Wednesday August 28

- MATLAB Basics
- MATLAB Plots
- MATLAB Examples

Lecture # 3

Friday August 30

- MATLAB Fundation
- Textbook Examples
- Short Quiz

MATLAB WORKSHOP

- Lecture # 3
- Friday August 30
- MATLAB Plots
- MATLAB Fundation
- Textbook Examples
- Short Quiz

MATLAB Basics

- Vectors and Matrices:(Cont.)

EXAMPLE:

>> a=2:3, b=[a 2*a;a/2 a]a = 2 3

b = 2.0000 3.0000 4.0000 6.0000 1.0000 1.5000 2.0000 3.0000

>> c=[b ; b]

c =2.0000 3.0000 4.0000 6.0000 1.0000 1.5000 2.0000 3.00002.0000 3.0000 4.0000 6.0000 1.0000 1.5000 2.0000 3.0000

MATLAB Basics

- Vectors and Matrices:

>> D=c(2:3, 2:3)

D = 1.5000 2.0000 3.0000 4.0000

- >> who Your variables are:D a b c
- >> whosName Size Bytes Class

D 2x2 32 double array a 1x2 16 double array b 2x4 64 double array c 4x4 128 double array

Grand total is 30 elements using 240 bytes

MATLAB Basics

- Vectors and Matrices:

Example:

>> a=magic(4)a= 16.0000 2.0000 3.0000 13.0000 5.0000 11.5000 10.0000 8.0000 9.0000 7.0000 6.0000 12.0000 4.0000 14.5000 15.0000 1.0000

>> sum(a) = sum(a') = [34 34 34 34]

- >> trace(a)= 34
- A(i, j) indexes row i, column j
- Indexing starts with 1, not zero.
- >>a(a, 3) = 3>>a(3, 1) = 39>>a(:, 3) = 3 10 6 15

MATLAB Basics

- Vectors and Matrices:
- >>a(2:3,3:4) =10 8 2 12
- >>a([1 4],[1 4]) =16 13 4 1
- >>a(8) = 14
- >>[1:3] + [4:6] =5 7 9
- A=zeros(2,2); B=(ones(3,2);

C = [ [A-1;B+1], [B+3;A-4] ],

C = -1 -1 4 4 -1 -1 4 4 2 2 4 4 2 2 -4 -4 2 2 -4 -4

MATLAB Basics

Plotting Elementary Functions:

MATLAB supports many types of graph and surface plots:

2 dimensions line plots (x vs. y), filled plots, bar charts, pie charts, parametric plots, polar plots, contour plots, density plots, log axis plots, surface plots, parametric plots in 3 dimensions and spherical plots.

To preview some of these capabilities and others as well, enter the command demos.

MATLAB Basics

Plotting Elementary Functions:

2-D plots: The plot command creates linear x-y plots; if x and y are vectors of the same length, the command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the elements of y.

MATLAB Basics

Plotting Elementary Functions:

>>%Example E1_2a of your textbook on page 23. (file name is E1_2.m)

>>t=-1:0.01:1;

>>f=4.5*cos(2*pi*t - pi/6);

>>%The following statements plot the sequence and label the plot

>>plot(t,f),title('Fig.E1.2a');

>>axis([-1,1,-6,6]);

>>xlabel('t');

>>ylabel('f(t)');

>>text(-0.6,5,'f(t) = A cos(wt + phi)');

>>grid;

Plot on next page

MATLAB Basics

Plotting Elementary Functions:

PLOT(X,Y) plots vector Y versus vector X.

TITLE('text') adds text at the top of the current plot.

XLABEL('text') adds text beside the X-axis on the current axis.

YLABEL('text') adds text beside the Y-axis on the current axis.

GRID, by itself, toggles the major grid lines of the current axes.

GTEXT('string') displays the graph window, puts up a cross-hair, and waits for a mouse button or keyboard key to be pressed.

SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes.

stemDiscrete sequence or "stem" plot. STEM(Y) plots the data sequence Y as stems from the x axis terminated with circles for the data value.

SEMILOGX(...) is the same as PLOT(...), except a logarithmic (base 10) scale is used for the X-axis.

SEMILOGY(...) is the same as PLOT(...), except a logarithmic (base 10) scale is used for the Y-axis..

MATLAB Basics

Plotting Elementary Functions:

By default, the axes are auto-scaled.

This can be overridden by the command axis. If c = [xmin,xmax,ymin,ymax] is a

4-element vector, then axis(c) sets the axis scaling to the prescribed limits.

By itself, axis freezes the current scaling for subsequent graphs; entering axis again returns to auto-scaling.

The command axis('square') ensures that the same scale is used on both axes.

For more information's on axis see help axis..

MATLAB Basics

Plotting Elementary Functions:

- >>%Example 1.2 of your textbook on page 24. (file name is E1_2d.m)
- >>t=-0.5:0.01:3;
- >>t0=0
- >>u=stepfun(t,t0)
- >>gprime=3.17*exp(-1.3*t).*cos(10.8*t + 1.15).*u;

% NOTE the use of the .* operator. The terms 3.17*exp(-1.3*t),

%cos(10.8*t + 1.15), and u are all vectors. We want the

% components of these vectors to be multiplied by the corresponding

% components of the other vectors, hence the need to use .* rather than *.

% The following statements plot the sequence and label the plot

- >>plot(t,gprime);
- >>axis([-.5,3,-3,2]);
- >>title('Fig.E1.2d');
- >>xlabel('t in seconds');
- >>ylabel('gprime(t)');
- >>text(-0.6,5,'f(t) = A cos(wt + phi)');
- >>grid;

MATLAB Basics

Plotting Elementary Functions:

Two ways to make multiple plots on a single graph are illustrated by

- >>t = 0:.01:2*pi;
- >>y1 = sin(t); y2=sin(2*t); y3=sin(4*t)
- >>plot(t,y1,y2,y3)
- and by forming a matrix Y containing the functional values as columns
- >>t = 0:.01:2*pi;
- >>y = [sin(t)', sin(2*t)', sin(4*t)']
- >>plot(t,y)
- Another way is with the hold command. The command hold freezes the current graphics screen so that subsequent plots are superimposed on it. Entering hold again releases the "hold". The commands hold on and hold off are also available.
- One can override the default linotypes and point types. For example,
- >>t = 0:.01:2*pi;
- >>y1 = sin(t); y2=sin(2*t); y3=sin(4*t)
- >>plot(t,y1,'--',y2,':',y3,'+')

MATLAB Basics

Plotting Elementary Functions:

- Colors Line Styles
- y yellow . point
- M magenta o circle
- C cyan x x-mark
- R red + plus
- G green - solid
- B blue * star
- W white : dotted
- K black -. Dashdot
- -- dashed

More mark types are; square(s), diamond(d), up-triangle(v), down-triangle(^), left-triangle(<), right-triangle(>), pentagram(p), hexagram(h)

See also help plot for more line and mark color.

MATLAB Basics

Plotting Elementary Functions:

The command subplot can be used to partition the screen so that up to four plots can be viewed simultaneously. See help subplot.

- Example for use of subplot:
- >>% Line plot of a chirp
- >> x=0:0.05:5;
- >> y=sin(x.^2);
- >> subplot(2,2,1), plot(x,y);
- >> % Bar plot of a bell shaped curve
- >> x = -2.9:0.2:2.9;
- >> subplot(2,2,2), bar(x,exp(-x.*x));
- >> % Stem plot
- >> x = 0:0.1:4;
- >> subplot(2,2,3), stem(x,y)
- >> % Polar plot
- >> t=0:.01:2*pi;
- >> subplot(2,2,4), polar(t,abs(sin(2*t).*cos(2*t)));

MATLAB Basics

Loading and Saving:

- When using MATLAB, you may wish to leave the program but save the vectors and matrices you have defined.
- SAVE, Save workspace variables to disk.SAVE FILENAME saves all workspace variables to the binary "MAT-file" named FILENAME.mat.
- The data may be retrieved with LOAD.
- If FILENAME has no extension, .mat is assumed. SAVE, by itself, creates the binary "MAT-file" named 'matlab.mat'.
- It is an error if 'matlab.mat' is not writable.
- To save the file to the working directory, type
- >>save filename
- SAVE FILENAME X saves only X.
- SAVE FILENAME X Y Z saves X, Y, and Z.where "filename" is a name of your choice. To retrieve the data later, type.

MATLAB Basics

Loading and Saving:

- LOAD Load workspace variables from disk.
- LOAD FILENAME retrieves all variables from a file given a full pathname or a MATLABPATH relative partial pathname (see PARTIALPATH).
- If FILENAME has no extension LOAD looks for FILENAME and FILENAME.mat and treats it as a binary "MAT-file".
- If FILENAME has an extension other than .mat, it is treated as ASCII.LOAD, by itself, uses the binary "MAT-file" named 'matlab.mat'. It is an error if 'matlab.mat' is not found.LOAD FILENAME X loads only X.LOAD FILENAME X Y Z ... loads just the specified variables.
- >>load x, y, z
- See help save and help load for more information..

MATLAB Basics

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.
- All of the MATLAB file in EE 327 textbook are contained in M-files that are available at the site http://www.csee.wvu.edu/~jalali.

MATLAB Basics

M-Files:

The following describes the use of M-files on a PC version of

MATLAB.

- MATLAB requires that the M-file must be stored either in the working directory or in a directory that is specified in the MATLAB path list.
- For example, consider using MATLAB on a PC with a user-defined M-file stored in a directory called "\MATLAB\MFILES";.
- Then to access that M-file, either change the working directory by typing cd\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 \MATLAB\matlabrc.m file.
- Temporary modification to the path is accomplished by typing path(path,'\matlab\mfiles') from within MATLAB.

MATLAB Basics

M-Files:

- The M-files associated with this textbook should be downloaded from the EE 327 site and copied to a subdirectory named "\MATLAB\users"; and then this directory should be added to the path.
- The M-files that come with MATLAB are already in appropriate directories and can be used from any working directory.

MATLAB Basics

M-Files Functions:

- As an example of 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)
- MATLAB M-files are most efficient when written in a way that utilizes matrix or

vector operations.

MATLAB Basics

Loops and If statements (Control Flow):

- Loops and if statements are available, but should be used sparingly since they are computationally inefficient.
- An example of the use of the command for is

for k=1:10,

x(k) = cos(k);

end

This creates a 1x10 vector x containing the cosine of the positive

integers from 1 to 10.

- This operation is performed more efficiently with the commands

k = 1:10;

x = cos(k);

- which utilizes a function of a vector instead of a for loop.

MATLAB Basics

If statements:

- An if statement can be used to define conditional statements.
- An example is

if(a <= 2),

b = 1;

elseif(a >=4)

b = 2;

else

b = 3;

end

- The allowable comparisons between expressions are >=, <=, <, >, ==, and ~=.

MATLAB Basics

While Loops statements (Control Flow):

- While for loop evaluates a group of commands a fixed number of times,
- A while loop evaluates a group of statements an infinite number of times.
- The general form of a while loop is

while expression

commands…

end

The command… between the while and end statements are executed as

long as ALL expression are true.

- Example (computing the special MATLAB value eps. ESP is a variable it is different from esp.)

>>num=0; EPS=1;

>>while (1+EPS)>1

EPS=EPS/2;

num=num+1;

end

>>num

num = 53.

>>EPS=2*EPS

EPS= 2.2204e-16

MATLAB USED 16 digit so eps is near 10^-16.

MATLAB Basics

User Defined Variable:

- Several of the M-files written for this textbook employ a user-defined variable which is defined with the command input. For example, suppose that you want to run an M-file with different values of a variable T.
- The following command line within the M-file defines the value:

T = input('Input the value of T: ')

- Whatever comment is between the quotation marks is displayed to the screen when the M-file is running, and the user must enter an appropriate value.
- Use help command for: diary, save, load, who and whos find out more about them.

MATLAB Examples

- Some on line Demos and Examples.

Simulink

- Graphical block diagram capability
- Can drag and drop components (called blocks)
- Extensive library of blocks available
- DSP Blockset is one
- Real-time Workshop

Simulink

- An environment for building and simulating models.
- Continuous, discrete or hybrid systems
- Linear and nonlinear components
- Can simulate asynchronous events
- Closely integrated with MATLAB and toolboxes

Simulink Model

- A typical Simulink model includes Sources, Systems and Sinks.

Sinks

Systems

Sources

- Sinewaves
- Function Generators
- From MATLAB workspace
- From Disk Files

- Displays scopes
- FFT scopes
- To MATLAB workspace
- To disk files

- Interconnectionof Linear and Nonlinear blocks

Simulink Block Libraries

- Simulink contains block libraries, which contain components that can be used to build models.
- A block library can itself have other libraries as blocks. Example: When you first start Simulink:

Sinks is itself a

block library of

components

Building a Simulink Model

Model Window

Use left mouse button to

drag blocks to the

model window

Linear Blocks

Library

Sources Library

Connecting Blocks

Use the left mouse

button to click on a port

and drag a connection

Use the right mouse

button to click on a line

to drag a branch line

More Simulink Basics

- Double-click on a block to open its Dialog Box. Parameters for the block can be set in this box.
- Example: setting the amplitude, frequency, phase and sampling frequency of the sinewave source.
- Click on the HELP button on the Dialog Box for a block to launch the Web Browser opened at the HELP file for that component.
- After selecting a block, you can rotate, flip or resize it. These operations are useful in creating a more “readable” block diagram.

Setting Simulation Parameters

- The Simulation menu item on the model’s window can be used to set simulation parameters.
- You can specify the appropriate solver that is to be used. For discrete-time systems use
- the Fixed-step Discrete solver if there is only a single sample time.
- The Variable-step Discrete solver for multirate systems.
- You can also specify variables that are to be obtained from or returned to the MATLAB workspace.

- You can select portions of your model using the mouse and make them into a subsystem.
- You can created a masked subsystem, that hides the complexity of the subsystem from the user.

Download Presentation

Connecting to Server..