Dumb mistakes we make with MATLAB.

조회 수: 28 (최근 30일)
Matt Fig
Matt Fig 2011년 2월 22일
댓글: Bruno Luong 2022년 6월 1일
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?
  댓글 수: 5
Andrew Newell
Andrew Newell 2011년 2월 23일
편집: Walter Roberson 2016년 9월 21일
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.
Matt Fig
Matt Fig 2011년 2월 25일
Best answer was a toss-up between the top two vote getters.

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2011년 2월 22일
Entering
>> rand(100000)
instead of
>> rand(100000,1)
Hm. Why has my whole machine come to a grinding halt?
  댓글 수: 8
Naz
Naz 2011년 11월 5일
rand(10000) creates matrix of 10000x10000
rand(10000,1) creates matrix of 10000x1
In the first case you are likely to run out of memory. I think there is a default setting that defines how much memory Matlab can use.
Steven Lord
Steven Lord 2016년 9월 21일
The array size limit preference introduced in release R2015a can help avoid that.

댓글을 달려면 로그인하십시오.

추가 답변 (34개)

Andrew Newell
Andrew Newell 2011년 2월 22일
Trying to edit a command already visible in the Command Window:
>> x=3
x =
3
Now put the cursor up beside x=3 and try to change it to 4:
>> 4
Oh, right, I should be down here!
  댓글 수: 8
Sean de Wolski
Sean de Wolski 2011년 2월 22일
Andrew Newell about 2 hours ago
assert(Yup=vote)
Error: The expression to the left of the equals sign is not a valid target for an assignment.
+1 to Preview Window
Andrew Newell
Andrew Newell 2011년 2월 22일
It's a greedy algorithm.

댓글을 달려면 로그인하십시오.


Paulo Silva
Paulo Silva 2011년 2월 22일
forget to put ; in some vector and array operations and get the command line spammed.
  댓글 수: 2
Matt Fig
Matt Fig 2011년 2월 22일
Oh yeah. Been there, done that.
Sean de Wolski
Sean de Wolski 2011년 2월 22일
I do that all of the time. But just forgetting the ';' ONCE, isn't the bad part. I use the up arrow a lot and so then I rerun the same command w/out the damn ';'. One lost semicolon can stick around for awhile.

댓글을 달려면 로그인하십시오.


Andreas Goser
Andreas Goser 2011년 2월 23일
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
  댓글 수: 2
Andrew Newell
Andrew Newell 2011년 2월 23일
And the number of commands grows all the time - especially if you have been visiting the FEX a lot.
Jan
Jan 2011년 10월 31일
x = 1:10; eval('plot=x;'); plot(1:10);
This give different results when run in the command window or inside a function.

댓글을 달려면 로그인하십시오.


Oliver Woodford
Oliver Woodford 2011년 2월 22일
clear
Oops, I wanted to keep one of those variables.
  댓글 수: 2
Paulo Silva
Paulo Silva 2011년 2월 22일
I wonder if it's possible to undo such operations?
Sean de Wolski
Sean de Wolski 2011년 2월 22일
I almost never use clear. I downloaded 'keep' on the FEX and it is far better.
That is of course unless I take the "Nuke it from orbit" approach; for which I wrote a script: 'cll.m' >>clear;close all;clc

댓글을 달려면 로그인하십시오.


Matt Tearle
Matt Tearle 2011년 2월 22일
I've been using MATLAB for 15 years or so - I teach people how to use it - and, of course, I stress the important difference between * and .* ...
So guess what once caused me a couple of hours of frustrated debugging of an image reconstruction algorithm...
Physician, heal thyself! (And don't test your algorithm on square images)

Matt Tearle
Matt Tearle 2011년 2월 22일
More in keeping with the OP, and another in the "physician heal thyself" category:
[fiddling about at the command line, trying to work out some kinks in an algorithm]
x1 - x2 % looks mostly near zero, but big vector, so:
max(ans) % oops, I meant...
max(abs(ans)) % no, not *that* ans! ::sigh::
  댓글 수: 4
Matt Tearle
Matt Tearle 2011년 2월 23일
As I reenter commands I chide myself "thought you'd save those few keystrokes, didn't you..."
Daniel Armyr
Daniel Armyr 2011년 6월 20일
Yeah, I was tought not to use ans by some teacher way back. Using ans simply gets you into trouble.

댓글을 달려면 로그인하십시오.


Matt Fig
Matt Fig 2011년 2월 22일
Along the lines of the cyclist's popular mistake, I do this one often enough:
x = rand(1:100); % I meant: x = rand(1,100);
??? Error using ==> rand
Maximum variable size allowed by the program is exceeded.
  댓글 수: 3
Matt Fig
Matt Fig 2011년 2월 23일
I do this about twice a year. I would like to blame fat fingers, but the ":" isn't that close to the "," on the keyboard!
Jan
Jan 2011년 2월 23일
@Matt Fig: Use a German keyboard where the key are neighboring. I use it to create "zeros(1:100)" frequently.

댓글을 달려면 로그인하십시오.


Aurelien Queffurust
Aurelien Queffurust 2011년 9월 15일
When I say orally to my peers to type
rehash toolboxcache
in 99 cases out of 100 they type
rehash toolboxcash

Jan
Jan 2011년 2월 22일
The old EVAL bugs, only a little bit more concealed:
Marker = {'lank', 'rank'}; % Ankle markers
Trajectory = rand(100, 3, 2);
MagicAutoAssign(Marker, Trajectory);
plot(rank); % FAIL
% ---------------
function MagicAutoAssign(Marker, Trajectory)
for i = 1:numel(Marker)
assignin('caller', Marker{i}, Trajectory(:, :, i));
end
Now plotting "rank" fails, because Matlab calls the toolbox function RANK instead. But it works, if "rank" is accessed using an index:
plot(1:100, rank(:, 1)); % OK
It was even worse in Matlab < 2008a: Even "RANK" in uppercase letters was forwarded to the function in non-debug mode, but in debug mode the uppercase "RANK" was recognized as variable. So you can create an error, which disappears at debugging - worst case!
Simple conclusion: Never create variables dynamically.
  댓글 수: 1
Rik
Rik 2018년 8월 14일
That really is a terrible debug situation...

댓글을 달려면 로그인하십시오.


Matt Fig
Matt Fig 2011년 5월 1일
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!
  댓글 수: 4
Matt Fig
Matt Fig 2011년 5월 2일
Look at the Edit link! It is calling to you!
Andrew Newell
Andrew Newell 2011년 5월 2일
Must ... resist ...

댓글을 달려면 로그인하십시오.


Steven
Steven 2011년 11월 4일
I often use != instead of the unusual ~=
  댓글 수: 2
Walter Roberson
Walter Roberson 2011년 11월 4일
http://zork.net/~sneakums/no-perl.svg
Jan
Jan 2011년 11월 4일
I had a "if a~=b" instead of "if a!=b" in a C-mex function. It even produced the correct result - usually.

댓글을 달려면 로그인하십시오.


Andrew Newell
Andrew Newell 2011년 2월 22일
The case of the misplaced transpose:
v1'*v2
instead of
v1*v2'
  댓글 수: 2
Matt Tearle
Matt Tearle 2011년 2월 22일
especially when these are very long row vectors... and there's no semicolon at the end of that line.
Andrew Newell
Andrew Newell 2011년 2월 22일
At least if there's no semicolon, you notice right away!

댓글을 달려면 로그인하십시오.


Jan
Jan 2011년 2월 22일
편집: Jan 2017년 10월 2일
c = {'a', 'b', 'c'}
c(2) = ''
>> c = {'a', 'c'}
Ups. I meant C{2} = ''. Another variant:
c = cell(1, 100);
c(:) = ''
>> c = {}
Better: c(:) = {''} to get a cell of empty strings.

Michael Quinn
Michael Quinn 2011년 3월 4일
>> exit
instead of
>> edit
  댓글 수: 2
Matt Fig
Matt Fig 2011년 3월 4일
Interesting. I never use EXIT, so that probably couldn't happen to me!
Steven Lord
Steven Lord 2017년 10월 2일
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.)

댓글을 달려면 로그인하십시오.


Knut
Knut 2013년 3월 5일
for i = 1:3
disp(exp(i*pi));
end
Instead of:
for i = 1:3
disp(exp(1i*pi));
end

Kye Taylor
Kye Taylor 2013년 4월 24일
>> close al
Error using close (line 111)
Specified window does not exist.
Dammit!

Adam
Adam 2016년 9월 21일
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.

Andrew Newell
Andrew Newell 2011년 2월 22일
Rejoice - now you can do it object-oriented style!
>> ME = MException
??? Error using ==> MException
Not enough input arguments
>> ME = MException.last
ME =
MException
Properties:
identifier: 'MATLAB:minrhs'
message: 'Not enough input arguments.'
cause: {0x1 cell}
stack: [0x1 struct]
Methods
  댓글 수: 2
Matt Fig
Matt Fig 2011년 2월 22일
Except I was using MATLAB 7.01!
Jiro Doke
Jiro Doke 2011년 2월 22일
Even with this, you can make the same mistake:
>> MException.lst
??? No appropriate method, property, or field lst for class MException.
>> MException.last
ans =
MException
Properties:
identifier: 'MATLAB:noSuchMethodOrField'
message: 'No appropriate method, property, or field lst for class MException.'
cause: {}
stack: [0x1 struct]
Methods

댓글을 달려면 로그인하십시오.


Andrew Newell
Andrew Newell 2011년 2월 22일
While in the debugger, typing quit instead of dbquit kills Matlab!
(My earlier version of this answer may have been too cryptic.)

Jan
Jan 2011년 2월 22일
Working:
n = datenum(datestr(now, 29), 29)
Failing (Matlab 2009a):
n = datenum(datestr(now, 30), 30)
>> Failed to lookup month of year.
DATENUM(S, F) needs a string as format specifier F. If F is numerical, it is interpreted as pivot year. With F=29 DATENUM works on accident only.

Jan
Jan 2011년 3월 3일
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.
  댓글 수: 2
Matt Fig
Matt Fig 2011년 3월 3일
That is one mistake I have not made.
Jan
Jan 2011년 3월 3일
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.

댓글을 달려면 로그인하십시오.


Jan
Jan 2011년 4월 4일
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!

Jan
Jan 2011년 5월 27일
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.

Ben Mitch
Ben Mitch 2011년 5월 27일
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')

Grzegorz Knor
Grzegorz Knor 2011년 9월 15일
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
  댓글 수: 2
Walter Roberson
Walter Roberson 2011년 9월 15일
Too bad we cannot "lock down" structures to prevent new fields from being added.
Jan
Jan 2011년 9월 15일
@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.

댓글을 달려면 로그인하십시오.


Jan
Jan 2011년 10월 31일
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
  댓글 수: 2
the cyclist
the cyclist 2011년 10월 31일
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().
Jan
Jan 2011년 10월 31일
permute()? I'd expect reshape() to do the equivalent operation without the smart choice of the dimension.

댓글을 달려면 로그인하십시오.


Shatrughan
Shatrughan 2011년 11월 4일
have anyone tried typing "Why" in the command prompt? MATLAB gives funny responses..just carry on typing for fun.. :)
  댓글 수: 1
Image Analyst
Image Analyst 2012년 2월 4일
I've listed some other Easter Eggs in http://www.mathworks.com/matlabcentral/answers/2001-what-matlab-easter-eggs-do-you-know

댓글을 달려면 로그인하십시오.


Jan
Jan 2012년 2월 4일
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.
  댓글 수: 9
Eric Sampson
Eric Sampson 2013년 4월 24일
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 :)
Eric Sampson
Eric Sampson 2013년 4월 24일
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! :)

댓글을 달려면 로그인하십시오.


Jan
Jan 2012년 5월 8일
편집: Jan 2012년 9월 16일
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.
  댓글 수: 2
Jan
Jan 2013년 4월 24일
What is required to display the string '\default' in an UICONTROL???
Walter Roberson
Walter Roberson 2013년 4월 24일
Maybe \\default ?

댓글을 달려면 로그인하십시오.


Geoff
Geoff 2012년 5월 10일
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.
  댓글 수: 4
Daniel Shub
Daniel Shub 2012년 5월 10일
I believe the name at one point meant Matrix Laboratory
Sean de Wolski
Sean de Wolski 2012년 5월 10일
It still does!

댓글을 달려면 로그인하십시오.


Jan
Jan 2017년 10월 3일
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

Michael Richards
Michael Richards 2020년 9월 15일
fig = figure('CloseReqFcn',@error_prone_fcn)
presses x button
error
alt-f4
error
tries close matlab
error
task manager > end task
error
  댓글 수: 1
Steven Lord
Steven Lord 2020년 9월 15일
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

댓글을 달려면 로그인하십시오.


DGM
DGM 2022년 6월 1일
편집: DGM 2022년 6월 1일
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.

Bruno Luong
Bruno Luong 2022년 6월 1일
Use 'end' to index an empty array.
  댓글 수: 1
Bruno Luong
Bruno Luong 2022년 6월 1일
a = [];
a(end) = 3
Array indices must be positive integers or logical values.
ugly work around
a = [];
a(max(1:end):end) = 3

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming Utilities에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by