Monday, February 9, 2009

Ploting Axes in Matlab

1. Initial

MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. This section describes a few of the most important graphics functions and provides examples of some typical applications.

The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.

For example, to plot the value of the sine function from zero to 2, use
t = 0:pi/100:2*pi;
y = sin(t);
plot(t,y)



Multiple x-y pairs create multiple graphs with a single call to plot. MATLAB automatically cycles through a predefined (but user settable) list of colors to allow discrimination between each set of data. For example, these statements plot three related functions of t, each curve in a separate distinguishing color:
y2 = sin(t-.25); y3 = sin(t-.5); plot(t,y,t,y2,t,y3)
It is possible to specify color, linestyle, and markers, such as plus signs or circles, with:
plot(x,y,'color_style_marker')
color_style_marker is a 1-, 2-, or 3-character string (delineated by single quotation marks) constructed from a color, a linestyle, and a marker type:
For example, the statement:
plot(x,y,'y:+')

plots a yellow dotted line and places plus sign markers at each data point. If you specify a marker type but not a linestyle, MATLAB draws only the marker.

2. Figure Windows

The plot function automatically opens a new figure window if there are no figure windows already on the screen. If a figure window exists, plot uses that window by default. To open a new figure window and make it the current figure, type
figure
To make an existing figure window the current figure, type
figure(n)
where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this window.


3. Adding Plots to an Existing Graph

The hold command allows you to add plots to an existing graph. When you type
hold on

MATLAB does not remove the existing graph; it adds the new data to the current graph, rescaling if necessary. For example, these statements first create a contour plot of the peaks function, then superimpose a pseudocolor plot of the same function:

[x,y,z] = peaks; contour(x,y,z,20,'k') hold on pcolor(x,y,z) shading interp

The hold on command causes the pcolor plot to be combined with the contour plot in one figure.


4. Subplots

The subplot function allows you to display multiple plots in the same window or print them on the same piece of paper. Typing
subplot(m,n,p)
breaks the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along first the top row of the figure window, then the second row, and so on. For example, to plot data in four different subregions of the figure window,
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)


5. Imaginary and Complex Data

When the arguments to plot are complex, the imaginary part is ignored except when plot is given a single complex argument. For this special case, the command is a shortcut for a plot of the real part versus the imaginary part. Therefore,
plot(Z)

where Z is a complex vector or matrix, is equivalent to

plot(real(Z),imag(Z))
For example
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')

draws a 20-sided polygon with little circles at the vertices.


6. Controlling Axes

The axis function has a number of options for customizing the scaling, orientation, and aspect ratio of plots.

Ordinarily, MATLAB finds the maxima and minima of the data and chooses an appropriate plot box and axes labeling. The axis function overrides the default by setting custom axis limits,
axis([xmin xmax ymin ymax])

axis also accepts a number of keywords for axes control. For example

axis square

makes the entire x-axes and y-axes the same length and

axis equal

makes the individual tick mark increments on the x- and y-axes the same length. So

plot(exp(i*t))

followed by either axis square or axis equal turns the oval into a proper circle.


axis auto


returns the axis scaling to its default, automatic mode.

axis on

turns on axis labeling and tick marks.

axis off

turns off axis labeling and tick marks.

The statement

grid off

turns the grid lines off and

grid on


turns them back on again.

7. Axis Labels and Titles

The xlabel, ylabel, and zlabel functions add x-, y-, and z-axis labels. The title function adds a title at the top of the figure and the text function inserts text anywhere in the figure. A subset of Tex notation produces Greek letters, mathematical symbols, and alternate fonts. The following example uses \leq for , \pi for , and \it for italic font.
t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'\it{Note the odd symmetry.}')


8. Mesh and Surface Plots

MATLAB defines a surface by the z-coordinates of points above a grid in the x-y plane, using straight lines to connect adjacent points. The functions mesh and surf display surfaces in three dimensions. mesh produces wireframe surfaces that color only the lines connecting the defining points. surf displays both the connecting lines and the faces of the surface in color.

9. Visualizing Functions of Two Variables

To display a function of two variables, z = f (x,y), generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. Then use these matrices to evaluate and graph the function. The meshgrid function transforms the domain specified by a single vector or two vectors x and y into matrices X and Y for use in evaluating functions of two variables. The rows of X are copies of the vector x and the columns of Y are copies of the vector y.

To evaluate the two-dimensional sinc function, sin(r)/r, between x and y directions:

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z)




In this example, R is the distance from origin, which is at the center of the matrix. Adding eps avoids the indeterminate 0/0 at the origin.

10. Images

Two-dimensional arrays can be displayed as images, where the array elements determine brightness or color of the images. For example,
load durer
whos

shows that file durer.mat in the demo directory contains a 648-by-509 matrix, X, and a 128-by-3 matrix, map. The elements of X are integers between 1 and 128, which serve as indices into the color map, map. Then
image(X)
colormap(map)
axis image


reproduces Dürer's etching shown at the beginning of this book. A high resolution scan of the magic square in the upper right corner is available in another file. Type
load detail
and then use the uparrow key on your keyboard to reexecute the image, colormap, and axis commands. The statement
colormap(hot) 

adds some twentieth century colorization to the sixteenth century etching.


11. Printing Graphics

The Print option on the File menu and the print command both print MATLAB figures. The Print menu brings up a dialog box that lets you select common standard printing options. The print command provides more flexibility in the type of output and allows you to control printing from M-files. The result can be sent directly to your default printer or stored in a specified file. A wide variety of output formats, including PostScript, is available.

For example, this statement saves the contents of the current figure window as color Encapsulated Level 2 PostScript in the file called magicsquare.eps:
print -depsc2 magicsquare.eps

It's important to know the capabilities of your printer before using the print command. For example, Level 2 Postscript files are generally smaller
and render more quickly when printing than Level 1 Postscript. However, not all PostScript printers support Level 2, so you need to know what
your output device can handle. MATLAB produces graduated output for surfaces and patches, even for black and white output devices. However,
lines and text are printed in black or white.

Thursday, February 5, 2009

Simulink Introduction

Simulink (Simulation and Link) is an extension of MATLAB. It works with MATLAB to offer modeling, simulating, and analyzing of dynamical systems under a graphical user interface (GUI) environment. The construction of a model is simplified with click-and-drag mouse operations. Simulink includes a comprehensive block library of toolboxes for both linear and nonlinear analysis. Models are hierarchical, which allow using both top-down and bottom-up approaches. As Simulink is an integral part of MATLAB, it is easy to switch back and forth during the analysis process and thus, the user may take full advantage of features offered in both environments. This tutorial presents the basic features of Simulink and is focused on control systems. Very useful for engineering field. This tutorial has been written for Simulink v.5 and v.6 It is upward and backward version compatible.

Getting Started

To start a Simulink session, you'd need to bring up Matlab program first.

From Matlab command window, enter:

>> simulink

Alternately, you may click on the Simulink icon located on the toolbar as shown:



Simulink's library browser window like one shown below will pop up presenting the block set for model construction.
To see the content of the blockset, click on the "+" sign at the beginning of each toolbox. To start a model click on the NEW FILE ICON as shown in the screenshot above. Alternately, you may use keystrokes CTRL+N. A new window will appear on the screen. You will be constructing your model in this window. Also in this window the constructed model is simulated. A screenshot of a typical working (model) window is shown below:


To become familiarized with the structure and the environment of Simulink, you are encouraged to explore the toolboxes and scan their contents. You may not know what they are all about at first, but perhaps you could catch on the organisation of these toolboxes according to their categories. For instance, you may see that the Control System toolbox consists of the Linear Time Invariant (LTI) system library and the MATLAB functions can be found under Function and Tables of the Simulink main toolbox. A good way to learn Simulink (or any computer program in general) is to practice and explore. Making mistakes is part of the learning curve. So, fear not you should be!
A simple model is used here to introduce some basic features of Simulink. Please follow the steps below to construct a simple model.

STEP 1: CREATING BLOCKS.

From BLOCK SET CATEGORIES section of the SIMULINK LIBRARY BROWSER window, click on the "+" sign next to the Simulink group to expand the tree and select (click on) Sources.

















A set of blocks will appear in the BLOCKSET group. Click on the Sine Wave block and drag it to the workspace window (also known as model window).


Now you have established a source of your model.

NOTE: It is advisable that you save your model at some point early on so that if your PC crashes you wouldn't loose too much time reconstructing your model.

I am going to save this model under the filename: "sinexample1". To save a model, you may click on the floppy diskette icon . or from FILE menu, select Save or using keystrokes CTRL+S. All Simulink model file will have an extension ".mdl". Simulink recognises file with .mdl extension as a simulation model (similar to how MATLAB recognises files with the extension .m as an MFile).
Continue to build your model by adding more components (or blocks) to your model window. We'll continue to add a Scope from Sinks library, an Integrator block from Continuous library, and a Mux block from Signal Routing library.

NOTE: If you wish to locate a block knowing its name, you may enter the name in the SEARCH WINDOW (at Find prompt) and Simulink will bring up the specified block.

To move the blocks around, simply click on it and drag it to a desired location. Once you've dragged over all necessary blocks, the workspace window should consist of the following components:


You may remove (delete) a block by simply clicking on it once to turn on the "select mode" (with four corner boxes) and use the DEL key or keys combination CTRL-X.

STEP 2: MAKING CONNECTIONS

To establish connections between the blocks, move the cursor to the output port represented by ">" sign on the block. Once placed at a port, the cursor will turn into a cross "+" enabling you to make connection between blocks.
A sine signal is generated by the Sine Wave block (a source) and is displayed by the scope. The integrated sine signal is sent to scope for display along with the original signal from the source via the Mux, whose function is to mutiplex signals in form of scalar, vector, or matrix into a bus.

STEP 3: RUNNING SIMULATION

You now may run the simulation of the simple system above by clicking on the play button . Alternately, you may use keystrokes CTRL+T, or choose Start submenu (under Simulation menu).
Double click on the Scope block to display of the scope.


To view/edit the parameters, simply double click on the block of interest.

Handling of Blocks and Lines

The table below describes the actions and the corresponding keystrokes or mouse operations (Windows versions).

Actions Keystokes or Mouse Actions
Copying a block from a library Drag the block to the model window with the left button on the mouse OR use select the COPY and PASTE from EDIT menu.
Duplicating blocks in a model Hold down the CTRL key and select the block with the left mouse drag the block to a new location.
Display block's parameters
Double click on the block
Flip a block CTRL-F
Rotate a block (clockwise 90 deg @ each keystroke)
CTRL-R
Changing blocks' names
Click on block's label and position the cursor to desired place.
Disconnecting a block
hold down the SHIFT key and drag the block to a new location
Drawing a diagonal line
hold down the SHIFT key while dragging the mouse with the left button
Dividing a line move the cursor to the line to where you want to create the vertex and use the left button on the mouse to drag the line while holding down the SHIFT key

Annotations

To add an annotation to your model, place the cursor at an unoccupied area in your model window and double click (left button). A small rectangular area will appear with a cursor prompting for your input.

To delete an annotation, hold down the SHIFT key while selecting the annotation, then press the DELETE or BACKSPACE key. You may also change font type and colour from FORMAT menu. Make sure that the block is selected before making the change.



Hope this useful. Thanks for visiting.