I get a parade of questions about which variables are available to nested functions and which variables, used in nested functions,
are part of the nesting function workspace. So today I thought I'd address this topic. For more information, you can read
this documentatio...
I get a parade of questions about which variables are available to nested functions and which variables, used in nested functions,
are part of the nesting function workspace. So today I thought I'd address this topic. For more information, you can read
this documentation.
function data = yoyo1()
% Note that data is an output here
data = 2
end
function yoyo2(in)
% Here, data is shared with the variable 'data'
% in blahblah's workspace
data = in;
end
end
You can see that there is the variable, in each function, named data. The question is, however, do they all refer to the same entity? And the answer is 'no.' Surprised? Let me explain. yoyo1 essentially declares data to be a local variable and not shared because of data's presence on the output argument list. The same would be true if data showed up on the input argument list instead, or if it showed up on both. However, yoyo2, which has no mention of data in its arguments lists, shared the variable data that is in blahblah's workspace. So calling yoyo2 changes the value of data in blahblah but calling yoyo1 does not.
Truisms about Variable Scope with Nested Functions
When you call an M-file containing a nested function, sufficient analysis is done on the M-file to determine which variables
are shared and which functions share them.
If a variable is in a nested function and appears in at least one of input or output argument lists for that function, then,
even if it's name matches a name in the nesting function's workspace, the two variables refer to different entities. This
is true even if other nested functions share the variable in the nesting function.
For a variable in a nested function to be shared with the nesting function, the variable must appear in the code of (i.e.,
be referred to or used in) nesting function. This is true even if you don't need to use the variable in the nesting function
but want multiple nested functions to share the variable.
You can't poof variables into nested function workspace. If need to do some debugging and want to create new variables, you can declare
them global and then assign to them. For more detail, read the documentation about Restrictions on Assigning to Variables.
Your Thoughts?
In the code I showed, I made sure to highlight the variables that are shared by printing them in italic. Especially for those
of you who do not care for the implementation we chose for nested functions, would some visual affordance such as this make
the situation more tenable for you? Let me know here.
At The MathWorks, we continue to explore ways to ease your programming learning curve and help you write better code. As
such, we have been discussing how stringent to make the messages in mlint with respect to catching errors. Currently, MATLAB doesn't make any particular reco...
At The MathWorks, we continue to explore ways to ease your programming learning curve and help you write better code. As
such, we have been discussing how stringent to make the messages in mlint with respect to catching errors. Currently, MATLAB doesn't make any particular recommendation about checking to be sure
you know which error you got before moving forward. Is that a really good idea? We aren't sure and thought find out your
thoughts on this.
Let me show you two snippets of code trying to accomplish basically the same task. I will discuss pros and cons of each.
Note, I will be using the new MException syntax for try and catch though you can do similar things using the older lasterror mechanism as well.
Snippet #1
try
doSomething;
doMore;
catch myException
cleanUpHere;
maybeThrowOwnNewException;
end
Snippet #2
try
doSomething;
doMore;
catch myException
expectedExceptionID = 'MATLAB:dimagree';
if strcmp(myException.identifier,expectedExceptionID)
cleanUpHereAndMaybeThrowError;
else
doDifferentCleanUp;
throwUnexpectedException;
end
end
Pros and Cons
snippet #1 is shorter than snippet #2
snippet #1 never checks that the caught error is the expected one
snippet #2 does two different operations, depending on whether the error was expected or not
when snippet #1 does throw its own new exception, since it didn't look at the actual one, the cause may not be correct or
meaningful to the user
There's No catch
Another related question arises if the try is not paired with a catch.
What Do You Think M-Lint Should Do?
For the first example, neither code snippet is outright "wrong." Moreover, there are cases, no doubt, where no matter what
the actual error is, you have no choice but to do a particular set of operations. However, that clearly isn't always so.
So, how forceful would you like to see M-Lint be for the case of snippet #1? Would getting a message there (though not a
red one) be helpful?
What about the situation in which there is no catch accompanying the try? Again, there may be a few cases where this makes sense, but typically that won't be so.
Let us know your thoughts about these questions here.
One of MATLAB's features is being able to customize plots. But some of the customization may not need to be done by hand
and can instead be controlled programmatically. Let me show you a set of these having to do with plotting lines.
Contents
P...
One of MATLAB's features is being able to customize plots. But some of the customization may not need to be done by hand
and can instead be controlled programmatically. Let me show you a set of these having to do with plotting lines.
If you make a plot by successively adding lines, all the lines, by default, have the same color and linestyle.
m3 = magic(3);
plot(m3(:,1));
hold on
plot(m3(:,2))
plot(m3(:,3))
hold off
As you can see, it's very hard (impossible) to tell which line is which.
Manually Control Color and Style
I can distinguish the lines by using different colors and linestyles. Here's one way to do it.
plot(m3(:,1),'r');
hold on
plot(m3(:,2),':b')
plot(m3(:,3),'g--')
hold off
Vectorizing Line Drawing
I can instead vectorize the line drawing.
plot(m3)
What you see here is the MATLAB cycles through colors to distinguish the plots. How many colors and which ones? Does MATLAB
ever cycle through the linestyles? You can find out answers to these questions in the documentation on LineStyle and Color as well as some answers in this article.
Default Line Properties
Let's see what properties lines in MATLAB have. First I'll create a line and then get the properties.
Notice two particular properties, Color and LineStyle. get shows me the current values.
get(h,'Color')
ans =
0 0 1
set allows me to see the choices for that property.
set(h,'LineStyle')
[ {-} | -- | : | -. | none ]
How Do axes Fit in?
Each line has a color and a linestyle, and they each have defaults, so what determines the behavior when I plotted multiple
lines and got different colors? That's related to a property of axes which we can see here.
get(gca)
ActivePositionProperty = outerposition
ALim = [0 1]
ALimMode = auto
AmbientLightColor = [1 1 1]
Box = on
CameraPosition = [2 5.5 17.3205]
CameraPositionMode = auto
CameraTarget = [2 5.5 0]
CameraTargetMode = auto
CameraUpVector = [0 1 0]
CameraUpVectorMode = auto
CameraViewAngle = [6.60861]
CameraViewAngleMode = auto
CLim = [0 1]
CLimMode = auto
Color = [1 1 1]
CurrentPoint = [ (2 by 3) double array]
ColorOrder = [ (7 by 3) double array]
DataAspectRatio = [1 2.5 1]
DataAspectRatioMode = auto
DrawMode = normal
FontAngle = normal
FontName = Helvetica
FontSize = [10]
FontUnits = points
FontWeight = normal
GridLineStyle = :
Layer = bottom
LineStyleOrder = -
LineWidth = [0.5]
MinorGridLineStyle = :
NextPlot = replace
OuterPosition = [0 0 1 1]
PlotBoxAspectRatio = [1 1 1]
PlotBoxAspectRatioMode = auto
Projection = orthographic
Position = [0.13 0.11 0.775 0.815]
TickLength = [0.01 0.025]
TickDir = in
TickDirMode = auto
TightInset = [0.0392857 0.0404762 0.00892857 0.0190476]
Title = [166.002]
Units = normalized
View = [0 90]
XColor = [0 0 0]
XDir = normal
XGrid = off
XLabel = [163.002]
XAxisLocation = bottom
XLim = [1 3]
XLimMode = auto
XMinorGrid = off
XMinorTick = off
XScale = linear
XTick = [ (1 by 11) double array]
XTickLabel = [ (11 by 3) char array]
XTickLabelMode = auto
XTickMode = auto
YColor = [0 0 0]
YDir = normal
YGrid = off
YLabel = [164.002]
YAxisLocation = left
YLim = [3 8]
YLimMode = auto
YMinorGrid = off
YMinorTick = off
YScale = linear
YTick = [ (1 by 11) double array]
YTickLabel = [ (11 by 3) char array]
YTickLabelMode = auto
YTickMode = auto
ZColor = [0 0 0]
ZDir = normal
ZGrid = off
ZLabel = [165.002]
ZLim = [-1 1]
ZLimMode = auto
ZMinorGrid = off
ZMinorTick = off
ZScale = linear
ZTick = [-1 0 1]
ZTickLabel =
ZTickLabelMode = auto
ZTickMode = auto
BeingDeleted = off
ButtonDownFcn =
Children = [162.004]
Clipping = on
CreateFcn =
DeleteFcn =
BusyAction = queue
HandleVisibility = on
HitTest = on
Interruptible = on
Parent = [1]
Selected = off
SelectionHighlight = on
Tag =
Type = axes
UIContextMenu = []
UserData = []
Visible = on
Well, hmmmm -- so many properties. Let me point out the two that are the ones to focus on for now.
Note: using gca is really only for debugging or illustration. Normally a handle should be gotten from the chosen axes and that handle specifically should be used.
axes Properties ColorOrder and LineStyleOrder
There are two axes properties that you can set to help you make the lines in your plots follow a pattern of color and linestyle. To see how
these work, let's set the defaults for these properties at the root of the handle graphics hierarchy and experiment.
Now you see that MATLAB first cycles over the colors using the first linestyle, then again cycles over the colors with the
second linestyle, etc., eventually cycling over the linestyles again as well.
Do You Override the Defaults?
Do you override the line plotting defaults? Do you do this manually or by setting the defaults as I have shown here? Let
me know here how you avoid hand-updating your plots.
The book Matrix Computations by Gene Golub and Charles
Van Loan sits on the bookshelves of many MathWorks employees.
Professor Golub, one of the founding members of the Stanford
University computer science department, is a revered figure in the
area of numerical analysis and matrix computations.
We...
The book Matrix Computations by Gene Golub and Charles
Van Loan sits on the bookshelves of many MathWorks employees.
Professor Golub, one of the founding members of the Stanford
University computer science department, is a revered figure in the
area of numerical analysis and matrix computations.
We were very sorry at MathWorks to hear that Professor Golub passed
away last month at the age of 75. His contributions will live
on in modern scientific and engineering computing.
Today I’d like to introduce a guest blogger, Jiro Doke (email: Jiro.Doke@mathworks.com), who is an applications engineer here at The MathWorks. He used MATLAB in his life prior to The MathWorks, and one of his
interests is data visualization.
Contents
...
Today I’d like to introduce a guest blogger, Jiro Doke (email: Jiro.Doke@mathworks.com), who is an applications engineer here at The MathWorks. He used MATLAB in his life prior to The MathWorks, and one of his
interests is data visualization.
In my graduate work, I used MATLAB extensively for doing analysis and visualization. Often times, the plots that I created
were used for my publications. It was then when I started to explore the flexibility of Handle Graphics to customize MATLAB
plots in order to create publication-quality graphics. Ultimately, I was able to use MATLAB almost exclusively for my plots.
Let me walk you through the step-by-step process of how I did it. I'm using some fabricated data, but the plot is very similar
to the ones I generated for my research.
Load Data
load data
Create Basic Plot
First, I plot my data to create the crude visualization
To make it more publication-quality, I make the following changes to the line properties, including the errorbar widths. In
my opinion, using thicker lines and larger markers greatly improves the "look" of my graphics. It's quite subjective, but
I select them based on how much data is on the graph. I select the appropriate "crowdedness" (balance of dark and white space):
Since many publications accept EPS formats, I select fonts that are supported by PostScript and Ghostscript. Anything that's
not supported will be replaced by Courier. I also define tick locations, especially when the default is too crowded.
This looks great! One thing that I may want to change is the way the dotted and dashed lines look. Notice that the dots are
too small. So, I wrote a simple function that goes into the EPS file and modifies the line definitions. I have posted the
function, fixPSlinestyle, on the File Exchange.
And there you go. I have automated the process of creating publication-quality graphics. Handle Graphics give you advanced control of how graphics look. In case you didn't know, MATLAB allows you to quickly take a MATLAB script
and publish a formated report (HTML, Word, LaTeX, XML, PPT), where the figures are automatically converted to various graphics format,
including EPS. This document was created using publish.
Your Examples
Tell us here about some of the cool things you do with Handle Graphics to make your figures look prettier.
In my personal history using computers, I have learned to embrace debuggers to help me understand what's going on in my code.
Contents
Short List of Lesser Known Debugging Commands
An Example
First Experiment
Stopping for a Caught Erro...
In my personal history using computers, I have learned to embrace debuggers to help me understand what's going on in my code.
Here's my short list of some useful debugging commands that might be less well known, especially for those of you who primarily use the interactive debugger as part of the MATLAB
editor:
Let's set up an example so you can see what's going on. I first make sure my debugger state is all cleared up and then create
a struct which I will then test to see if a particular field exists.
dbclear all
s.fred = 1;
dbtype isfieldTryE
1 function tf = isfieldTryE(s,f)
2 %ISFIELD True if field is in structure array.
3 % F = ISFIELDTRYE(S,'field') returns true if 'field' is the name of a field
4 % in the structure array S.
5 %
6 % See also GETFIELD, SETFIELD, FIELDNAMES.
7
8 tf = true;
9 try
10 tmp = s.(f);
11 catch E
12 % I don't care why it failed.
13 tf = false;
14 end
15
16
First Experiment
What happens if I ask to see if a particular field exists, and ask for MATLAB to stop if there's an error?
dbstop iferror
isfieldTryE(s,'fred')
ans =
1
isfieldTryE(s,'freddy')
ans =
0
What you can see is that testing for either an existing or non-existent field sails on through.
And I get the same behavior if I try to stop only for an appropriate message identifier.
ans =
1
Caught-error breakpoint was hit in isfieldTryE at line 10. The error was:
Reference to non-existent field 'freddy'.
ans =
0
Now when I ask for a non-existent field, the debugger stops in the catch block. And to resume, I use
dbcont
Common Issues
There are a few common issues that puzzle people when debugging. They include:
breakpoints disappearing when debugging. This is often caused by a clear all in code being run. See, for example, this post.
name collisions. These are caused either by using a variable name the same as a name for a MATLAB function, or having multiple
functions with the same name. Using which can help you figure out what's going on if you realize there's a nameclash.
variables not being present. This is often an issue of not understanding scoping in MATLAB, including inputs and outputs of functions, what workspace graphics callbacks execute in, scripts versus functions.
Handy Tip
Here's a useful tip I use, for debugging, or sometimes to just find out the signature of a function. Using
and you will see the first line of the file displayed. If you write your code as we tend to do at The MathWorks, the first
line of a file containing functions will be the function definition line. Voila, you have the signature!
Other Debugging Gotchas and Tips?
You might find some additional debugging tips on Doug's blog.
Some people like the keyboard command or omitting terminating semicolons but I prefer to debug without editing my code, when possible.
Do you have other tips to share that you find helpful? Post them here.
What makes MATLAB unique? You have your choice regarding which element unique returns when there are repeated values in an array. What I wonder about is why it matters.
Contents
Which Index to Return
unique in Action
What I Don't Know
...
What makes MATLAB unique? You have your choice regarding which element unique returns when there are repeated values in an array. What I wonder about is why it matters.
helptext =
UNIQUE Set unique.
B = UNIQUE(A) for the array A returns the same values as in A but
with no repetitions. B will also be sorted. A can be a cell array of
strings.
UNIQUE(A,'rows') for the matrix A returns the unique rows of A.
[B,I,J] = UNIQUE(...) also returns index vectors I and J such
that B = A(I) and A = B(J) (or B = A(I,:) and A = B(J,:)).
[B,I,J] = UNIQUE(...,'first') returns the vector I to index the
first occurrence of each unique value in A. UNIQUE(...,'last'),
the default, returns the vector I to index the last occurrence.
See also UNION, INTERSECT, SETDIFF, SETXOR, ISMEMBER.
you will see that you can get the index value returned. By default, unique returns the last index, but you are also request the first one. Additionally, you can look for unique rows, something especially
useful for character data.
unique in Action
Here's a quick demonstration of unique acting on a vector of birthdates in my extended family (just the day of the month) and the unique values.
What I can't think of is why I care about the index. I am sure there are applications where it matters because there is related
data that needs to come along. But what does the occurrence order have to do with anything?
Your Examples
Would you please share your code examples in which it mattered to you which instance of a non-unique element you captured?
Let me know here.