Auxiliary plt functions and .m files

All these functions are individual .m files in the main plt folder except for datestr and metricp which are included inside plt.m. These functions solve problems often associated with creating GUI applications in Matlab, such as adding traces, special plot types, figure positioning and text formatting issues.


(serial date
number to
s = plt('datestr',datenum,fmt) is similar to s = datestr(datenum,fmt) except that it displays the time with 1 millisecond resolution instead of 1 second resolution used by the Matlab datestr function. Let's compare the results from plt's and Matlab's date string functions:
  a = now;
  datestr(a,13) 03:51:46
  plt('datestr',a,13)  03:51:46.153
  datestr(a,14) 03:51:46 AM
  plt('datestr',a,14) 03:51:46.153 AM
  datestr(a,0) 31-Mar-2015 03:51:46
  plt('datestr',a,0) 31-Mar-2015 03:51:46.153
  datestr(a) 31-Mar-2015 03:51:46
  plt('datestr',a) 31-Mar-15 03:51:46.153
For a description of the allowable formats type help datestr. Note that the formats can include arbitrary formatting strings or integers representing 32 standardized formats. Notice carefully the last example in the table above since the returned date format when no format code is specified is different between plt's and Matlab's datestr function. (2 vs 4 character year).


(figure positioning)
Normally the position of a figure window is specified in pixels as: [xleft ybottom width height] relative to the monitor, meaning that xleft = 1 refers to the leftmost position of the monitor. However it usually is more convenient to specify the figure relative to the usable screen space, which takes into account the space needed for the taskbar as well as the space needed for the window borders and title bar.

Consider the following two methods of creating a new figure window:

figure('BackgroundColor',[0 0 .1],'Position',p);
figure('BackgroundColor',[0 0 .1],'Position',figpos(p);

In the first method, the pixel coordinates in p are relative to the full screen which especially with a multi-window GUI makes it impossible to make good use of the screen area without knowing where the taskbar is and other desktop variables. In the second line however the coordinates in p are relative to a pre-defined clear area of the screen which are converted into absolute screen coordinates by figpos (this routine).

To accomplish this, figpos must know the screen area that can accommodate the Matlab figure window. It gets this information from the screencfg.m routine which normally can determine the optimal border area automatically. (See the description of the screencfg function below.) The way screencfg is called in figpos, it will only optimize the border area the first time it is called. After that it gets the border area from the saved value (which is stored in the 'border' application data variable of the root object). This means that if you move or resize the taskbar you should restart Matlab so that the border area is recalculated. (If you don't want to restart Matlab, instead you could type the command rmappdata(0,'border') or equivalently setappdata(0,'border','').)

First I will first explain how figpos computes the figure position from the input argument, although you may find it easier to understand by skipping ahead to the examples below.

In rare situations, you may want to specify the screen position using the standard Matlab convention [left bottom width height] referenced to the screen without reference to the border areas. Of course, then you don't need to call figpos in the first place ... except for the fact that figpos is called automatically by plt, so we need a way to bypass the usual figpos processing. The way to do that is simply to place an "i" after any element in the 1x4 vector. For example:

figpos([40 50i 600 500]) returns the vector [40 50 600 500].

It doesn't matter which element contains the "i", and in fact you can put the "i" in all 4 elements if you like, i.e. figpos([400 50 600 500]*1i);

Suppose you call figpos([p1 p2 p3 p4]) where all the terms are real and p3 and p4 are both positive. This is called "size priority mode" because the getting the figure size correct takes priority over getting the left/bottom position in the specified place. In this mode, figpos will return [left bottom width height] where:
   width  = the smaller of p3 and the maximum clear width available
   height = the smaller of p4 and the maximum clear height available
   left   = p1 + left border width. However if this position would make the
            right edge of the figure overflow the clear space available, then
            the left edge is moved rightward just far enough so the figure fits.
   bottom = p2 + bottom border width. However if this position would make the
            top edge of the figure overflow the clear space available, then
            the bottom edge is moved down just far enough so the figure fits.
Suppose you call figpos([p1 p2 -p3 p4]), i.e. the same as the calling sequence above except that the 3rd element is negative. The height and bottom values are computed exactly as shown above (size priority), but the width and left values are now computed as follows (position priority):
   left   = p1 + left border width.
   width  = p3. However if this width would make the right edge of the figure
            overflow the clear space available, then the width is reduced by
            just enough so that the figure fits.
Suppose you call figpos([p1 p2 p3 -p4]), i.e. the 4th element is negative. The left and width values are computed exactly as shown in the first all positive (size priority mode) but the bottom and height values are now computed as follows (position priority):
   bottom = p2 + bottom border width.
   height = p4. However if this height would make the top edge of the figure
            overflow the clear space available, then the height is reduced
            by just enough so that the figure fits.
If you call figpos([p1 p2 -p3 -p4]), then both horizontal and vertical coordinates use the position priority method described above.

An optional 5th value in the input vector is allowed to allocate extra space for the title bar. You may want to do this if you know that a menu bar or toolbar will be enabled since that will make the title bar larger. Since this is not accounted for in the border area set up by screencfg, enabling these features could cause the top edge of the figure to fall off the top edge of the screen. For example:

figpos([p1 p2 p3 p4 48]) would allocate 48 extra pixels in the vertical space which would be enough for the menu bar (about 21 pixels high) and one toolbar (about 27 pixels high).

The default left/bottom coordinates are [5 5] which are used if they are not supplied. For example:

figpos([730 550]) gives the same results as figpos([5 5 730 550]).
figpos([730 550 21]) gives the same results as figpos([5 5 730 550 21]).

You also may specify only the figure length or the figure width and let figpos calculate the missing size parameter based on the most appropriate aspect ration. For example figpos([1000 0]) and figpos([0 944]) both give the same results as figpos([1000 944]). This particular aspect ratio (1.006) was chosen so that if you plot a circle, the resulting figure is actually looks circular rather than elliptical. For example, this line plots a perfect circle using 600 points:

plt(exp((1:600)*pi*2i/599),'pos',[800 0])

The following examples may clarify the specification described above:

The first example creates 5 plots of the same size placed on the screen so that all the plots are as far away from each other as possible. The first four plots are placed right at the edge of the screen at the four corners, except not so close that any of the figure borders disappear and of course not obscuring the taskbar no matter where the taskbar is placed. On a small screen even the first four figures would overlap. On a large screen, the first four figures would not overlap, but the fifth figure would overlap the corners of the other four (unless the screen had an exceptionally high resolution).
   y = rand(1,100);  sz = [700 480];     % data to plot and figure size
   plt(y,'pos',[ 0   0  sz]);            % bottom left corner
   plt(y,'pos',[Inf  0  sz]);            % top left corner
   plt(y,'pos',[ 0  Inf sz]);            % bottom right corner
   plt(y,'pos',[Inf Inf sz]);            % top right corner
   p = get(findobj('name','plt'),'pos'); % get positions of all 4 plt figures
   plt(y,'pos',mean(cell2mat(p))*1i);    % put 5th plot at the average position
The "*1i" in the above line is necessary to prevent figpos from adjusting the position using the current border information. The raw pixel location is used because the get('pos') command returns raw pixel coordinates. With the "*1i" removed, the last figure would not be at the exact arithmetic mean position (although possibly the error might be too small to notice.

The next example also creates four figures at the corners of the screen, although this time, the first figure is a fixed size and the remaining figures are tiled so as to fill all the remaining space on the screen.
   plt(y,'pos',[ 0   0   600  400]); % figure 1 is placed at the lower left corner
   plt(y,'pos',[ 0  440  600 -Inf]); % use all the remaining space above fig1
   plt(y,'pos',[615  0  -Inf  400]); % use all the remaining space to the right of fig1
   plt(y,'pos',[615 440 -Inf -Inf]); % use all the remaining space not used by figs 1-3
Note that in the example above an extra 15 pixels in width and 40 pixels in height is used to create a small gap between the four figures.

In addition to the examples above, a good way to appreciate the value of the figpos function is to run demoplt.m and cycle thru all the plt demo programs using the "All Demos" button. Notice how well the various windows are placed on the screen. You will appreciate the intelligence of the placement even more if you are able to rerun the demos using a different screen resolution and a different taskbar location. Without the figpos function, many of the demos would have to be more complicated to place their figures at appropriate screen positions.


(spawn a
Some GUI applications open a figure window containing moving images (such as these examples from the plt demo folder:

bounce run
curves go
dice3 run
movbar run
pltmap run
pltsq run
wfall run

(Note, the optional argument 'run' or 'go' tells the application to start updating the moving image as soon as it starts.) Using a straightforward implementation of such a GUI program, the program would run continuously to update the moving image and therefore the command prompt would not reappear in the command window after starting the program. This means that you couldn't enter any more Matlab commands in the command window until the GUI program terminated, or the program was instructed to stop updating the figure. The funcStart function provides a way to initiate the moving image and return immediately so that the command window is again able to accept new Matlab commands. The eight programs listed above serve as examples of how to use funcStart to achieve this objective.

funcstart({@func arg1 arg2 ...},d);

If funcStart is nested less than d levels below the command prompt then funcStart calls function @func (with arguments if supplied) and then returns to the calling function immediately without waiting for @func to complete. If funcStart is called from a more deeply nested function, then @func is called but it doesn't return to the calling function until @func is complete.

funcstart({@func arg1 arg2 ...});

When called without the 2nd argument, d defaults to 2. This means that after @func is initiated, execution of the calling function will continue immediately only if funcStart was called from the command prompt or from the top level of a script or function. Otherwise @func is called but it doesn't return until @func is complete.

Because @func is called as a timer function callback, two extra arguments are added at the beginning of the argument list. This means that arg1 will actually be the 3rd argument of @func and arg2 will be the 4th, etc.

Note: If you don't care about the nesting depth you can use funcstart(v,Inf);


[Ret1, Ret2] = plt('metricp',x);

Used to convert a number to a form using standard metric prefixes. Ret1 is the metric prefix string that is most appropriate for displaying the value x, and Ret2 is the x multiplier. This is often useful for scaling plots to avoid awkward scientific notation in the axis labels.
  x = .3456E-6;
  sprintf('%.3e Volts',x) 3.456e-007 Volts
  [pfix mult] = plt('metricp',x);
  sprintf('%.1f %sVolts',x*mult,pfix)   345.6 Nano-Volts


(float to ascii)
s = Pftoa(fmtstr,x) returns in string s an ascii representation of the scalar number x according to the formatting string fmtstr.

If fmtstr is of the form '%nW' then swill be the string representation of x with the maximum resolution possible while using at most n characters.

If fmtstr is of the form '%nV' then swill be the string representation of x with the maximum resolution possible while using exactly n characters.

If fmtstr is of the form '%nw' then s will be the string representation of x with the maximum resolution possible while using at most n characters - not counting the decimal point if one is needed.

If fmtstr is of the form '%nv' then s will be the string representation of x with the maximum resolution possible while using exactly n characters - not counting the decimal point if one is needed.

The lower case formats (v,w) are typically used to generate strings to fit into gui objects of a fixed width. The reason the decimal point is not counted is that with the proportional fonts generally used in these gui objects, the extra space taken up by the decimal point is insignificant.

With all four format types, if the field width is too small to allow even one significant digit, then '*' is returned.

fmtstr may also use any of the numeric formats allowed with sprintf. For example:

Pftoa('%7.2f',x) is equivalent to sprintf('%7.2f',x)

Normally Pftoa must include exactly two arguments, but there is one exception. The command Pftoa('test') or equivalently Pftoa test will create a test file called PftoaTest.txt. Looking at the examples in this text file may help you better understand the differences between the four new format specifiers.

Normally you won't call Pftoa directly since calling it thru prin is more general and just as concise. (See prin below.)


& fprintf
s = prin(fmtstr,OptionalArguments);
s = prin(FID,fmtstr,OptionalArguments);

Converts the OptionalArguments to a string s using the format specified by fmtstr. Note that this does the same thing as sprintf or fprintf (with the same calling sequences) except that prin offers some additional features including four extra formatting codes. prin calls the Pftoa function described below to implement the new formatting codes. FID is usually a value returned from fopen but can also be a 1 or a 2 to direct the result to the Matlab command window. For a complete description of this function, see prin.pdf (in the main plt folder). You can view that help file most quickly by simply typing prin (i.e. with no arguments) at the Matlab command prompt.


(publication plots)
Although plt is usually used for data exploration it can also be used to create publication quality plots by using a suitable set of parameters. This can be simplified by calling pltpub which calls plt with these defaults:

 The 'COLORdef',0 parameter   to select a white plot background  
 The 'TraceID','' parameter       to remove the TraceID box
 The 'NoCursor' option   to remove the cursor objects
 The '-All' option   to remove the menu box

The demo programs pub0.m, pub1.m, and pub2.m, and xChart.m demonstrate the use of pltpub and also shows that any of the pltpub defaults may be overridden.

If the first pltpub argument is 'Cpick' (as done in the pub0 and xChart demos) then the ColorPick action is assigned to all plt lines, axes, and text elements. This makes it easy to make final color adjustments before the screen capture. It also has the (usually desirable) side effect that all mouse driven zoom and pan operations are disabled. (Don't include this argument if you need those mouse driven operations.)

Consider creating your own functions similar to pltpub with sets of plt defaults that you use frequently.


(add plt trace)
pltt is so central to the way plt is used that this auxiliary function was given its own section. Please refer to the Adding traces section.


bar plots)  
This function is used to plot a series of vertical bars. It doesn't do any plotting itself, but returns an array which is then plotted using plt (or even plot). For example, suppose you want to plot 4 vertical bars at x-axis locations 2,3,7,8. Each bar is to start at y=0 and extend up to y=6,6,5,1 respectively. The following line would meet this objective:

plt(Pvbar([2 3 7 8],0,[6 6 5 1]);

Normally all three Pvbar arguments are vectors the same length, however in this case since the lower y position of each bar is the same a constant may be used for the 2nd argument.

Although you don't have to know this to use it, Pvbar returns a complex array which is interpreted correctly by plt or plot to display the desired sequence of vertical bars. plt and plot displays complex arrays by plotting the real part of the array along the x-axis and the imaginary part of the array along the y-axis. The trick that Pvbar uses to display a series of lines with a single array stems from the fact that NaN values (not a number) are not plotted and can be used like a "pen up" command. (The Pebar and Pquiv functions described below use this same trick.)

The general form of the Pvbar function call is:

v = Pvbar(x,y1,y2)

If the inputs are row or column vectors, this would return a complex column vector which when plotted with plt or plot would produce a series of vertical bars (of the same color) at x-axis locations given by x. y1 and y2 specify the lower and upper limits of the vertical bar. It doesn't matter whether you list the upper or lower limit first. If y1 is a scalar, Pvbar expands it to a constant vector of the same size as y2.

Suppose you wanted to plot 30 red bars (specified by length 30 column vectors xr,yr1,yr2) and 30 green bars (specified by length 30 column vectors xg,yg1,yg2). You could do this with two calls to Pvbar as in:


That's probably the first way you would think of, but if xr and xg happen to be the same length (as in this case) you can accomplish the same thing with a single call to Pvbar:

plt(Pvbar([xr xg],[yr1 yg1],[yr2 yg2]));

The second form is especially convenient when plotting many bar series (generally each series in a different color). Interestingly, if you use plot instead of plt first form will not work so you must use the second form.

Note that Pvbar will expand the second argument in either dimension if needed. So for instance in the example above, if ya1 and yb1 were the same you could just use ya1 as the second argument. Or suppose the base (lower limit) of the first series was always 0 and the base of the second series was always -1. Then you could use [0 -1] as the second argument. If the base of all the bars in all the series was the same value, then the second argument may be a scalar.

To see Pvbar in action, look at the example program pltvbar.m in the demo folder. This example also shows the use of the Pebar function described below.


(error bar
This function is used to plot a series of vertical bars similar to the above Pvbar function with the addition of a small horizontal "T" section on the top and bottom of each bar. This is commonly used to depict an error bound of a function, or a range of values that may be achieved by a certain function. Another difference with Pvbar is the way the lower and upper y positions of the bars are specified. With Pebar, the first two arguments (x,y) specify a reference position for each vertical bar, which is normally (but not strictly necessary) somewhere in the middle of the bar. The third/fourth arguments (l,u) specify the distance between the reference position and the lower/upper end (respectively) of the vertical bar.

The general form of the Pebar function call is:

e = Pebar(x,y,l,u,dx)

The position of the bottom of the error bars is y-l and the top is y+u. The last argument (dx) is a scalar that specifies the width of the horizontal Ts as a percentage of the average x spacing. The last two arguments are optional. If dx is not specified it defaults to 30 (%). If u is not specified it defaults to l (the 3rd argument) in which case the reference coordinates become the midpoints of the error bars. e,x,y,l,u are generally vectors or matrices of the same size, the only exception being that l and u are are allowed to be scalar. Read the description of Pvbar above for an explanation of how vector and matrix inputs are interpreted.

To see Pebar in action, look at the example program pltvbar.m in the demo folder. This example also shows the use of the Pvbar function described above.


(vector plots)
This function is used to plot a vector fields represented by a set of arrows with arbitrary head and tail locations. It doesn't do any plotting itself, but returns an array which is then plotted using plt (or even plot). For example, suppose you wanted to plot 3 arrows (all in the same color) with tail locations (4,9) (2,3) and (1,7). Also suppose you wanted each vector to be of length one, pointing up, down, and the the right respectively. This could be done as follows:


This can also be done using Pquiv's complex input form as follows:

tail = [4+9i;2+3i;1+7i]; head = [1i;-1i;1];

Note that row vectors could have been used instead of column vectors if desired. Now suppose in addition to those 3 vectors, you wanted to plot 3 more vectors (in a second color) with the same tail locations but pointing in the opposite direction. Using the previous assignments of tail and head, This could be done as follows:


Or you could do the same thing with a single call to Pquiv:

plt(Pquiv(tail*[1 1],head*[1 -1]));

Of course the equivalent 4 argument (real input) form of Pquiv could have been used as well.

There are 8 possible calling sequences for Pquiv depending on whether the input arguments are real or complex and on whether the optional arrow head size argument is included. Pquiv is smart enough to figure out which calling sequence you are using.

Calling sequence Tail coordinates Arrow width/length Arrow head size
q = Pquiv(A,B)   [real(A), imag(A)]   [real(B), imag(B)] 0.3
q = Pquiv(A,B,h) [real(A), imag(A)] [real(B), imag(B)] h
q = Pquiv(x,y,B) [x,y] [real(B), imag(B)] 0.3
q = Pquiv(x,y,B,h) [x, y] [real(B), imag(B)] h
q = Pquiv(A,u,v) [real(A), imag(A)] [u, v] 0.3
q = Pquiv(A,u,v,h) [real(A), imag(A)] [u, v] h
q = Pquiv(x,y,u,v) [x, y] [u, v] 0.3
q = Pquiv(x,y,u,v,h)   [x, y] [u, v] h

q,A,B are complex vectors or matrices
x,y,u,v are real vectors or matrices
h is a scalar (Arrow head size - relative to vector length)

Read in the Pvbar description above how complex values and NaNs are used to generate the desired display. To see Pquiv in action, look at the example program pltquiv.m in the demo folder.



A general purpose 3D surface (waterfall) display routine

Calling sequence:

  • All arguments are optional except for z which is a matrix containing the surface data.
  • Note that the arguments are arranged in Param/Value pairs.
  • However you may omit the Value part of the pair, in which case the default value of 1 is used.

pltwater recognizes the following 12 Param/Value pairs (case insensitive):

'go',1 The animation begins immediately as if you had pressed the start button.
'go' The same as above (since an omitted value is assumed to be one).
'run' The same as above. Note that all the sliders and check boxes mentioned below may be adjusted even when the display is running (animation).
'invert' The surface is displayed upside down.
'transpose' The surface is rotated by 90 degrees (x/y swapped).
'delay',v A pause of v milliseconds occurs between display updates. Whatever value (v) is supplied, it may be changed later using the slider.
'nT',v Determines how many traces will be visible initially. Later you may change the number of visible traces using the slider. If the nT parameter is not included, 40 traces will be used (initially).
'skip',v Initially v records (rows of z) are skipped between each record access. (e.g. if v=1 only every other record is used.) This value may be modified using the slider.
'dx',v Successive traces of the waterfall display are displaced by v pixels to the right which adds a visual perspective. (No perspective is perceived if v is zero.) This value may be modified with the slider.
'dy',v Successive traces of the waterfall display are displaced in the vertical direction by v percent of the Zaxis limits. This value may be modified using the slider.
'x',v Specifies the x values corresponding to each column of z. If this parameter is not supplied, the value 1:size(z,2) is used.
'y',v Specifies the y values corresponding to each row of z. If this parameter is not supplied, the value 1:size(z,1) is used.
'smooth',v Line smoothing is a line property in most versions of Matlab (although it is not supported in R2014b or later). If this parameter is not included then line smoothing is enabled when the display is running (animating) and is disabled otherwise. That behavior may be modified as follows:
  • 'smooth', 1   Line smoothing is always enabled
  • 'smooth',-1   Line smoothing is always disabled
  • 'smooth', 0   The default line smoothing mode as described above.
If you are using a version of Matlab that doesn't support line smoothing, pltwater will not enable line smoothing mode regardless of the setting of this parameter.

If a parameter is included in the pltwater argument list that is not one of the above 13 choices, then this parameter along with its corresponding value are passed onto plt. The most common plt parameters used in the pltwater argument list are:
       'TraceC'  'CursorC'  'FigBKc'     'LabelX'  'Pos'   'HelpText'
       'Title'   'FigName'  'Linewidth'  'LabelY'  'xy'
Refer to the wfalltst.m demo program to see an example of how to create an application using the pltwater function.


(screen configuration)
If called without an argument, screencfg attempts to determine the current screen borders automatically. For Windows based systems it does this by calling the auxiliary function workingArea.m (described below). For non-Windows based systems it does this using the WindowState property except for with older versions of Matlab which don't have this property. In that case it will use a java frame. For non-Windows systems, in unusual situations (such as with a very old Matlab version such as Matlab 6), the automatic procedure may fail. In that case, a warning is issued and the taskbar size and position defined in the file TaskbarSZ.m is assumed (which may be edited if needed). Unless you see such a warning you can ignore the rarely used TaskbarSZ.m file.

The input of this function (if supplied as a vector) as well as the output of this function may be either a 4 or 5 element row vector called the "border vector". This border vector is also saved in the 'border' application property value of the matlab root object.

If called with a vector argument, then the supplied argument is taken to be the new border vector.

If called with a scalar argument, then screencfg first looks for the 'border' application property value. If this property exists, then its value is returned and nothing further is done. However if the 'border' property does not exist, then screencfg will behave as if it was called without an argument (described above).

When a 4 element vector is used for the border vector, its form is [left bottom right top] where each number represents the number of pixels of clear space (i.e. not used for Matlab figures) that must exist at the four edges of the screen indicated. When a 5 element vector is used its form is:

[left bottom width height 0] The largest visible screen position in pixel units using the standard Matlab figure positioning scheme.
[left bottom width height 1] Same as above except that normalized coordinates are used.

When specifying the screen position using a vector input argument, either the 4 or 5 element form may be used and so the 'border' property may contain either a 4 or 5 element vector. (figpos handles either form.) However when screencfg is used to find the screen working area automatically (as it is typically used) it always returns the result as a 4 element vector (i.e. specifying the pixels of clear space required at the left, bottom, right, and top edges.


(find useble screen area)
For Windows based systems workingArea.m is called from screencfg.m (described above) to determine the portion of the screen where figure windows can be placed without overlapping the taskbar. Unfortunately, workingArea.m does not work with for non-Windows based systems so screencfg.m uses other methods for those systems. It's unlikely you will want to call workingArea.m directly when creating figure windows with plt, however you may find it useful when you are creating figure windows directly with Matlab's figure command. Here are some examples:

figure('OuterPosition',workingArea); creates a figure filling the entire usable screen area.
v = workingArea + [8 8 -16 -16];
similar to above, except it gives you an 8 pixel margin on all sides
w = workingArea;  p = [380 250];
figure('OuterPosition',[w(1:2) p]);
creates a 380 by 250 figure in the lower left corner of the working area
w = workingArea;  p = [380 250];
v = [w(1)+w(3)-380 w(2) p];
creates a 380 by 250 figure in the lower right corner of the working area
w = workingArea;  p = [380 250];
v = [w(1) w(2)+w(4)-250 p];
creates a 380 by 250 figure in the upper left corner of the working area
w = workingArea;  p = [380 250];
v = [w(1:2)+w(3:4)-p p];
creates a 380 by 250 figure in the upper right corner of the working area
w = workingArea;
v = [w(1)+w(3)-300 w(2) 300 w(4)];
creates the tallest 300 pixel wide figure as far to the right as possible
w = workingArea;
v = [w(1) w(2)+w(4)-200 w(3) 200];
creates the widest 200 pixel high figure as far to the top as possible