pBook‎ > ‎

Matlab


Class Example

posted Sep 11, 2014, 8:49 AM by Javad Taghia   [ updated Sep 11, 2014, 8:49 AM ]

Source: http://matlabmafia.wordpress.com/2010/11/27/enhanced-matlab-plotting-series-part-i/

We all know about Matlab’s unparalleled plotting capabilities.  The signature 3-D surface plot sitting on our desktop as a Matlab icon is a daily reminder.  The intent here is not to delve into surface or mesh plots, but to focus on simple 2-D plotting.

A Brief Background

First let me give a little background about how this plotting layer came about.  As an avid Matlab user, I spend most of my days staring at monitors filled with m-files and plots. Over time I began to realize that I preferred all of my plots to appear a certain way; and was spending much of my time formatting figures, axes and lines.  So I decided to develop an engine within Matlab that would handle all of my plotting. You can think of this as a layer between the coder and the low level Matlab plotting and formatting functions.  Almost immediately after creating this layer I recognized that I was substantially more efficient, and to top it off everything appeared exactly the way I wanted; too good to be true, right?.  After working with and developing this layer for some time now, I’ve added a substantial amount of functionality….I’m at the point where I couldn’t imagine having to revert back to interfacing directly with the low-level Matlab plot function.  So, in this series of articles I hope to explain what this magic “layer” is that I’ve been referring to.

So What is This Layer???

Before diving in, I must warn you that this “layer” I’ve been referring to is actually called a class.  Classes are used in a form of programming termed Object-Oriented Programming (OOP).  But don’t shy away simply because you haven’t used them.  We will walk through how the class is created to some extent.  I was brought up in Mechanical Engineering (ME) and know that ME’s (and other engineering disciplines) are rarely exposed to object-oriented programming (as I usually get the blank stare when I bring it up around my ME colleagues).  If you are interested, check out Matlab’s website about OOP @

http://www.mathworks.com/products/matlab/object_oriented_programming.html.

They do a nice job of providing an introduction and explaining the syntax.  Since OOP is something foreign to many branches of engineering, Matlab OOP may be one of our series in the near future.

Our Basic Plotting Object

Ok, so let’s get started.  In this first part of the series we are merely going to predefine a color scheme for our plots; specifically, line and axes properties.  It sounds simple, and is…but I have found this to be very useful for daily Matlab chores.

Let’s first begin by creating a blank class with an empty constructor (a function that runs when you instantiate the class), a few properties (attached variables local to our class) and one method (aka function).

Next lets add some properties to our class.  These properties will be used to define the style of a Matlab line object.  The comments in the code explain the intent of each property.

For now, just set GetAccess and SetAccess to public.  We will discuss what this means later in the series.  Also, the use of these properties may be a bit fuzzy at this point.  Keep going and this will become clear as we flesh out these properties.

Adding the Plot Method

Now lets incorporate a method (function) used to plot data.  This function will behave similar to Matlab’s plot function in that it accepts x and y vector data pairs as input arguments.  This plot function will draw the data onto the current axes while assigning the line properties defined within the class.

Defining Line Settings (Visual)

Now all we have to do is define a few line properties and the class should be ready for action.  For this task we will define a function that builds our color, marker and line type arrays.  This will then be called within in the constructor of the class.  Hence once the class is instantiated these properties of the class will get defined.  This is shown below.  We have defined unique properties for 4 different lines within the buildProperties function.  Notice the last statement initializes the plotCounter property to zero.

Putting the Plot Object to Work

Let’s try out the new mPlot class.  As shown below, instantiation of the class creates an instance of our mPlot object.  All of the properties that we have defined within the class definition file show up within the object.

Next test out the plot  method.  The simple loop

should produce

Asxis Control

posted Aug 31, 2014, 8:50 PM by Javad Taghia   [ updated Aug 31, 2014, 8:51 PM ]

Source, Axis scaling and appearance

Syntax

axis([xmin xmax ymin ymax])
axis([xmin xmax ymin ymax zmin zmax cmin cmax])
v = axis
axis auto
axis manual
axis tight
axis fill
axis ij
axis xy
axis equal
axis image 
axis square
axis vis3d
axis normal
axis off
axis on
axis(axes_handles,...)
[mode,visibility,direction] = axis('state')

Description

axis manipulates commonly used axes properties. (See Algorithm section.)

axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the current axes.

axis([xmin xmax ymin ymax zmin zmax cmin cmax]) sets the x-, y-, and z-axis limits and the color scaling limits (see caxis) of the current axes.

v = axis returns a row vector containing scaling factors for the x-, y-, and z-axis. v has four or six components depending on whether the current axes is 2-D or 3-D, respectively. The returned values are the current axes XLim,Ylim, and ZLim properties.

axis auto sets MATLAB® default behavior to compute the current axes limits automatically, based on the minimum and maximum values of xy, and z data. You can restrict this automatic behavior to a specific axis. For example, axis 'auto x' computes only the x-axis limits automatically; axis 'auto yz' computes the y- and z-axis limits automatically.

axis manual and axis(axis) freezes the scaling at the current limits, so that if hold is on, subsequent plots use the same limits. This sets the XLimModeYLimMode, and ZLimMode properties to manual.

axis tight sets the axis limits to the range of the data.

axis fill sets the axis limits and PlotBoxAspectRatio so that the axes fill the position rectangle. This option has an effect only if PlotBoxAspectRatioMode or DataAspectRatioMode is manual.

axis ij places the coordinate system origin in the upper left corner. The i-axis is vertical, with values increasing from top to bottom. The j-axis is horizontal with values increasing from left to right.

axis xy draws the graph in the default Cartesian axes format with the coordinate system origin in the lower left corner. The x-axis is horizontal with values increasing from left to right. The y-axis is vertical with values increasing from bottom to top.

axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the xy, and z directions.

axis image is the same as axis equal except that the plot box fits tightly around the data.

axis square makes the current axes region square (or cubed when three-dimensional). This option adjusts the x-axis, y-axis, and z-axis so that they have equal lengths and adjusts the increments between data units accordingly.

axis vis3d freezes aspect ratio properties to enable rotation of 3-D objects and overrides stretch-to-fill.

axis normal automatically adjusts the aspect ratio of the axes and the relative scaling of the data units so that the plot fits the figure's shape as well as possible.

axis off turns off all axis lines, tick marks, and labels.

axis on turns on all axis lines, tick marks, and labels.

axis(axes_handles,...) applies the axis command to the specified axes. For example, the following statements

h1 = subplot(221);
h2 = subplot(222);
axis([h1 h2],'square')

set both axes to square.

[mode,visibility,direction] = axis('state') returns three strings indicating the current setting of axes properties:

Output Argument

Strings Returned

mode

'auto' | 'manual'

visibility

'on' | 'off'

direction

'xy' | 'ij'

mode is auto if XLimModeYLimMode, and ZLimMode are all set to auto. If XLimModeYLimMode, or ZLimMode ismanualmode is manual.

Keywords to axis can be combined, separated by a space (e.g., axis tight equal). These are evaluated from left to right, so subsequent keywords can overwrite properties set by prior ones.

Drawline

posted Aug 29, 2014, 5:14 AM by Javad Taghia   [ updated Aug 29, 2014, 5:14 AM ]

For drawing line between two points use the function below:
function [] = drawline(p1, p2 ,color)
theta = atan2( p2(2) - p1(2), p2(1) - p1(1));
r = sqrt( (p2(1) - p1(1))^2 + (p2(2) - p1(2))^2);
line = 0:0.01: r;
x = p1(1) + line*cos(theta);
y = p1(2) + line*sin(theta);
plot(x, y , color)

and call it in your program as:
drawline([fx(i) fy(i)] ,[y(i,1) y(i,2)],'red')

Text Label

posted Aug 29, 2014, 3:39 AM by Javad Taghia   [ updated Aug 29, 2014, 3:39 AM ]

for i=1:1:length(y)
    plot (y(i,1),y(i,2), '*r')
    hold on
    grid on
    axis equal
  
    plot (y(i,4),y(i,5), '*b')
end
  strValues = strtrim(cellstr(num2str([y(:,1) y(:,2)],'(%d,%d)')));
  text(y(:,1),y(:,2),strValues,'VerticalAlignment','bottom');

Drawnow

posted Aug 29, 2014, 3:38 AM by Javad Taghia   [ updated Aug 29, 2014, 3:38 AM ]

We are going to use Matlab plotting capability to produce animation while we are simulating.
The essential command is "drawnow" and we can "pause" to slow down the animation.

for i=1:1:length(y)
    plot (y(i,1),y(i,2), '*r')
    hold on
    grid on
    axis equal
  
    plot (y(i,4),y(i,5), '*b')
    drawnow
    pause(0.1)
end

1-5 of 5