General
Follow


Matt Fig

Dumb mistakes we make with MATLAB.

Matt Fig on 22 Feb 2011
Latest activity Reply by Bruno Luong on 1 Jun 2022

O.k., admit it. Who has done this (or something that resulted in the same loss of info) before?
>> laster
??? Undefined function or variable 'laster'.
>> lasterr
ans =
Undefined function or variable 'laster'.
D'Oh! I need a ERRORBEFORELASTERR function.
What's one of your dumb MATLAB mistakes?
Bruno Luong
Bruno Luong on 1 Jun 2022
Use 'end' to index an empty array.
Bruno Luong
Bruno Luong on 1 Jun 2022
a = [];
a(end) = 3
Array indices must be positive integers or logical values.
ugly work around
a = [];
a(max(1:end):end) = 3
DGM
DGM on 1 Jun 2022
I spent a moment today trying to figure out why
outarray = logical(size(inarray)); % preallocate
didn't create a logical array with the same size as inarray.
I swear I must have brain damage, and with the caliber of forehead slap I needed, I can see how it would happen.
Michael Richards
Michael Richards on 15 Sep 2020
fig = figure('CloseReqFcn',@error_prone_fcn)
presses x button
error
alt-f4
error
tries close matlab
error
task manager > end task
error
Steven Lord
Steven Lord on 15 Sep 2020
Specifying 'force' with the close command will force the figure to close, bypassing its CloseRequestFcn.
fig = figure('CloseRequestFcn',@(varargin) error('No closing this figure!'));
close(fig) % Will not close the figure
close(fig, 'force') % Will close the figure
fig % This is now a handle to a deleted figure
Jan
Jan on 3 Oct 2017
I needed a short and confusing command for a demonstration:
eval = 1:255
eval eval
Error: "eval" was previously used as a variable, conflicting with its use here as the name of a function or command.
This works:
eval('eval')
>> 100 117 96 107
Adam
Adam on 21 Sep 2016
Since I happened across this old thread, one that continually catches me out since I work a lot with plotting of complex signals is to the effect of
figure; plot( mySignal )
hilbSignal = hilbert( mySignal )
hold on;
plot( hilbSignal );
Doh! Pretty spider's web, but not quite what I was looking for. One day I will remember I have complex data and that I actually want either the real or imaginary part! In this case I keep just thinking of the hilbert transform result as the imaginary part only that it adds.
Kye Taylor
Kye Taylor on 24 Apr 2013
>> close al
Error using close (line 111)
Specified window does not exist.
Dammit!
Knut
Knut on 5 Mar 2013
for i = 1:3
disp(exp(i*pi));
end
Instead of:
for i = 1:3
disp(exp(1i*pi));
end
Geoff
Geoff on 10 May 2012
Corrupting years of experience in other languages...
After using MatLab for several months now, I find that when I go back to writing C code I catch myself forgetting to put parentheses on my if statements and using single-quotes for my strings.
Sean de Wolski
Sean de Wolski on 10 May 2012
It still does!
Daniel Shub
Daniel Shub on 10 May 2012
I believe the name at one point meant Matrix Laboratory
Jan
Jan on 10 May 2012
And MATLAB with lower-case a, t, a, b. Can anybody explain, why MATLAB is written with an upper-case L frequently? I did this myself also. Has it been the official spelling in Matlab 4?
See Stevens confusion of ~= and != above.
Geoff
Geoff on 10 May 2012
Oh yeah I knew there was another... Writing comments with %. Grrrr
Jan
Jan on 8 May 2012
The strings 'default', 'remove', and 'factory' are not allowed as uimenu labels, see Ref: uimenu_props. To get the string 'default' as label, '\default' must be used.
This is another example for the bad magic strings. Imagine you want to create a bunch of uimenu s automatically using a list of words. Then the exception handling for these three words will be ugly and increase the program size without a real benefit.
[EDITED] The named strings have a special meaning for other handle graphics objects also, e.g. UICONTROLs:
uicontrol('String', 'default')
This doe not display 'default' in a button, but an empty string, because this is the default value:
get(0, 'defaultUIControlString')
To display 'default', 'factory', or 'remove', a leading backslash is required, see doc: setting-default-property-values:
uicontrol('String', '\default')
It would be smarter to use the backslash for the special commands, but this cannot be changed without breaking the backward compatibility.
Walter Roberson
Walter Roberson on 24 Apr 2013
Maybe \\default ?
Jan
Jan on 24 Apr 2013
What is required to display the string '\default' in an UICONTROL???
Jan
Jan on 4 Feb 2012
Although I never use clear all (see Answers: Bad CLEAR ALL), it appears in user-supplied code frequently. If all is defined as a variable, the behaviour might be unexpected:
clear all
b = 1;
all = 2;
clear all
whos
% Name Size Bytes Class Attributes
% b 1x1 8 double
If "all" is a variable, it is cleared, but the other variables are not touched.
[EDITED] The "clear all" behaviour is a typical example for the bad programming practize of using magic numbers. Here the string 'all' is magic, because it triggers a totally amnesia, if there is no variable of this name. It would be smarter to use invalid symbols for special commands, e.g. "$all". See Wiki: magic numbers and Wiki: magic strings.
Eric Sampson
Eric Sampson on 24 Apr 2013
P.S. I've also recently requested that TMW consider making the use of 'clear all' an M-lint/Analyzer warning, because it has side effects that trip people up (like clearing breakpoints & globals, flushing the M-file cache, etc). If you like the idea, call/email support and lend your vote to this enhancement request! :)
Eric Sampson
Eric Sampson on 24 Apr 2013
To be honest I think a lot of the functions that were created in early MATLAB versions are the ones that tend to have syntax issues like this... Since they've been around so long it would be hard for TMW to break backwards compatibility. As TMW hired more professional programmers over the years, instead of mathematicians/scientists doubling as programmers, things have improved IMHO, like your example about '-regexp'. Of course this is all personal opinion YMMV etc, and it's not intended to be a slight at all to TMW old-timers :)
Jan
Jan on 5 Mar 2013
@Walter: The magic strings let us make mistakes, when we forget to consider them. E.g. I forgot the escape character in a context menu, where I can move an object to its "default" position. It is in the nature of context menus, that an automatic unit-test cannot find this bug, but only an active user.
I'm sure most programmers omit a test for {'default', 'remove', 'factory'}, when they assign the string of buttons or menus dynamically.
Daniel Shub
Daniel Shub on 10 May 2012
@Jan, my point was that I don't use the CLEAR command in any of my programs. The magic strings in UIMENU is more problematic.
Walter Roberson
Walter Roberson on 9 May 2012
Magic strings are a MathWorks mistake, not a dumb mistake on our part.
Jan
Jan on 9 May 2012
The magic strings are not bound to the functional form.
"S = 'all'; clear(S);" behaves equivalently. See my next answer concerning magic strings in labels of UIMENUs.
I do not suffer from the magic string "all" for the CLEAR command, because I never overload the builtin function ALL and avoid a CLEAR('all') at all.
But the same problem concerns "clear('variables')", "clear('global')", "clear('functions')", "clear('import')" and "clear('classes')". Clearing an M-file of the same name is not possible and using the name "import" as a variable is not unlikely.
For the newer flag "-regexp" TMW has been so smart to use the minus to _unmagicalize_ the string. The same for "which <> -all" or "save -mat". The usage of magic constants without an escape character can and will lead to bugs or to large and ugly constructions to catch the exceptions.
Daniel Shub
Daniel Shub on 8 May 2012
I am not sure I see the use of magic strings in this case as particularly bad. Mostly because I don't use clear in my programming. In fact, clear is one of the few (doc, help, and edit being the others that come to mind) functions that I rarely call in its functional form.
Jan
Jan on 8 May 2012
And I should take the time to publish my functions unclear() and totallyunclear() in the FEX.
Daniel Shub
Daniel Shub on 8 May 2012
From now on I might just have to answer homework questions with code that has variable names of all and clear (and maybe builtin and str2func just to up the challenge).
Shatrughan
Shatrughan on 4 Nov 2011
have anyone tried typing "Why" in the command prompt? MATLAB gives funny responses..just carry on typing for fun.. :)
Image Analyst
Image Analyst on 4 Feb 2012
I've listed some other Easter Eggs in http://www.mathworks.com/matlabcentral/answers/2001-what-matlab-easter-eggs-do-you-know
Steven
Steven on 4 Nov 2011
I often use != instead of the unusual ~=
Jan
Jan on 4 Nov 2011
I had a "if a~=b" instead of "if a!=b" in a C-mex function. It even produced the correct result - usually.
Walter Roberson
Walter Roberson on 4 Nov 2011
http://zork.net/~sneakums/no-perl.svg
Jan
Jan on 31 Oct 2011
The process-first-non-singelton feature can be smarter than the user:
m = randi(4);
n = randi(4);
M = rand(m, n);
ColumnSum = sum(M); % DANGEROUS
If m is 1, the sum is calulated alog the 2nd dimension. Better:
ColumnSum = sum(M, 1); % Secure
NOTE: For min, max and std the 2nd input is not the dimension!
max([1, 2; 3, 4], 2) % >> [2, 2; 3, 4], elementwise maximun
max([1, 2; 3, 4], [], 2) % >> [2; 4], maximun along 2nd dimension
Jan
Jan on 31 Oct 2011
permute()? I'd expect reshape() to do the equivalent operation without the smart choice of the dimension.
the cyclist
the cyclist on 31 Oct 2011
The squeeze() command has similar dangers, when there are unanticipated singleton dimensions. In my experience, it is almost always possible, and wiser, to use permute() rather than squeeze().
Grzegorz Knor
Grzegorz Knor on 15 Sep 2011
Sometimes I make a typo in structure field name, for example:
my_struct.field1 = 1
and then:
my_struct.filed1 = 2
It produces:
my_struct =
field1: 1
filed1: 2
instead of:
my_struct =
field1: 2
Jan
Jan on 15 Sep 2011
@Walter: We can. I'm using a selftest function, which scans the source code and checks all symbols, which contain a dot. The structs are created in a dedicted function, and no other function is allowed to add further fields.
I care for a minimal edit-distance, e.g. I avoid S.mvc and S.mcv, which would be too susceptible for typos. Of course I never create fields by complicated EVAL commands or LOAD structs directly to the workspace.
Using OO methods would be a more convenient method to limit the definition of fields. But even for functional programs, OO strategies are important for writing reliable software.
Walter Roberson
Walter Roberson on 15 Sep 2011
Too bad we cannot "lock down" structures to prevent new fields from being added.
Aurelien Queffurust
Aurelien Queffurust on 15 Sep 2011
When I say orally to my peers to type
rehash toolboxcache
in 99 cases out of 100 they type
rehash toolboxcash
Ben Mitch
Ben Mitch on 27 May 2011
Moving into the Figure window, but in a similar spirit to the rand(100000) thing, I use this when I need an excuse to take a break...
data = randn(2, 1e6);
plot(data)
when I meant this...
plot(data')
Jan
Jan on 27 May 2011
Check if a path name contains a certain folder name anywhere
if any(findstr(PathName, '/Sub/')) ...
Because FINDSTR searches the shorter string in the longer one, the condition is true for the path name '/' also.
Modern Matlab version use STRFIND(String, Pattern) and afaik FINDSTR will be deprecated. But the program containing the example was developped under Matlab 5.3. Fixing the bug by changing FINDSTR to STRFIND is not trivial, if the strings are created dynamically, e.g. FINDSTR(a{i}, ['@', b{j}]).
At least in Matlab 2009a the toolbox functions contains a lot of these pitfalls, e.g. Signal\PMEM: "if ~isempty(findstr(flag, 'CORR')), ...", which triggers for 'OR' also.
Matt Fig
Matt Fig on 1 May 2011
Not so much with MATLAB, but with MATLAB answers. This one has bitten me several times.
I will edit an answer I had given earlier, in response to more questions or comments from the OP. Often the edit will be fairly lengthy, and so take some time. When I am done I check for spelling errors (usually) then hit the Submit button - at least that is what I should do. Sometimes I hit the Edit link, which causes the page to refresh! All typing lost ..... Aargh!
It would be nice if there simply was no Edit link available when editing (what is it there for anyway?), for dummies like me!
Andrew Newell
Andrew Newell on 2 May 2011
Must ... resist ...
Matt Fig
Matt Fig on 2 May 2011
Look at the Edit link! It is calling to you!
Matt Fig
Matt Fig on 2 May 2011
Sorry Andrew, at least I am not alone ;)
Haha, maybe if I bump this post I can infect more regular posters!
If they too complain, then perhaps TMW will remove the Edit button when editing is enabled...
Andrew Newell
Andrew Newell on 2 May 2011
You're a bad influence, Matt. I had never made this particular mistake - until you wrote about it!
Jan
Jan on 4 Apr 2011
I wanted to add the optimization flag /arch:SSE2 in my MEX call in Matlab 2009a:
mex -O OPTIMFLAGS="$OPTIMFLAGS /arch:SSE2" func.c
For a batch processing I need the functional form (or EVAL?!):
mex('-O', 'OPTIMFLAGS="$OPTIMFLAGS /arch:SSE2"', 'func.c')
>> ERROR: flag /arch:SSE2 is not recognized.
Ugly parser! The over-complicated BAT-> M-> PERL-> Compiler pipeline of the MEX command tries to be intelligent. This works:
mex('-O', 'OPTIMFLAGS="$OPTIMFLAGS', '/arch:SSE2"', 'func.c')
The string must be split inside the double quoted section, although these double quotes are used to avoid the splitting!
Michael Quinn
Michael Quinn on 4 Mar 2011
>> exit
instead of
>> edit
Steven Lord
Steven Lord on 2 Oct 2017
Go to the Preferences and expand the MATLAB > General > Confirmation Dialogs section. There's an entry, "Confirm before exiting MATLAB", that if you select it will bring up a dialog each time you try to quit MATLAB (normally. If you forcibly kill it from Task Manager, or if MATLAB crashes, it won't be able to show the dialog.)
Matt Fig
Matt Fig on 4 Mar 2011
Interesting. I never use EXIT, so that probably couldn't happen to me!
Jan
Jan on 3 Mar 2011
I've tried to start an instance of another Matlab version, but the current directory was a toolbox folder by accident:
In Matlab 6.5, Windows:
cd(fullfile(matlabroot, 'toolbox\matlab\strfun');
system('C:\Programme\Matlab\R2009a\bin\win32\MATLAB.exe &')
==> Matlab 2009a starts with a lot of warnings about finding M-files, which are builtin functions. Then the script STRNCMP (the help text only!) is attempted to execute as a function. Because this fails, the Matlab path contains just \toolbox\local. Without toolbox function the diagnosis was tedious.
I had a similar break down, after overloading STRCMP with a damaged version.
Jan
Jan on 3 Mar 2011
I'm glad to hear that. It is a mess and a silly waste of time. Another version of such faults:
M-script with the help text only in one folder:
\MFiles\Folder\MyFun.m
Compiled function for different platforms in specific folders, which are included in the path dynamically:
\MFiles\ForMatlab6\MyFun.dll
\MFiles\ForMatlab7\MyFun.mexw32
Now calling MyFun from the command line or another M-function fails, if \MFiles\Folder\ is the current folder: "Attempt to call the script MyFun as a function". Solution: CD to a neutral folder.
Matt Fig
Matt Fig on 3 Mar 2011
That is one mistake I have not made.
Matt Fig
Matt Fig on 25 Feb 2011
Best answer was a toss-up between the top two vote getters.
Andreas Goser
Andreas Goser on 23 Feb 2011
Overlaying command with variables:
plot=1:10;
plot(1:10)
ans =
1 2 3 4 5 6 7 8 9 10
Or command with commands like creating and own contrast.m function and then using MATLAB's CONTRAST function.
All this typicall leads to errors messages that are not helpful to detect the cause and only if you think of WHICH -ALL, you find it
Jan
Jan on 31 Oct 2011
x = 1:10; eval('plot=x;'); plot(1:10);
This give different results when run in the command window or inside a function.
Andrew Newell
Andrew Newell on 23 Feb 2011
And the number of commands grows all the time - especially if you have been visiting the FEX a lot.
Andrew Newell
Andrew Newell on 23 Feb 2011
My apologies to everyone while I learn how to edit comments. Here is my third try:
This is like David Lodge's "Humiliation Game" http://www.guardian.co.uk/books/2008/jun/13/david.lodge, except that admitting we're dumb doesn't cost us a job (unless we work for Matlab?) and everyone believes us.
Walter Roberson
Walter Roberson on 22 Feb 2011
Clicking on the above link might get you "page not found". If so, remove the trailing > from the URL.