Have you ever learned that something you were doing manually in MATLAB was already possible using a built-in feature? Have you ever written a function only to later realize (or be told) that a built-in function already did what you needed?
Two such moments come to mind for me.
1. Did you realize that you can set conditional breakpoints? Neither did I, until someone showed me that feature. To do that, open or create a file in the editor, right click on a line number for any line that contains code, and select Set Conditional Breakpoint... This will bring up a dialog wherein you can type any logical condition for which execution should be paused. Before I learned about this, I would manually insert if-statements during debugging. Then, after fixing each bug, I would have to delete those statements. This built-in feature is so much better.
2. Have you ever needed to plot horizontal or vertical lines in a plot? For the longest time, I would manually code such lines. Then, I learned about xline() and yline(). Not only is less code required, these lines automatically span the entire axes while zooming, panning, or adjusting axis limits!
Share your own Aha! moments below. This will help everyone learn about MATLAB functionality that may not be obvious or front and center.
(Note: While File Exchange contains many great contributions, the intent of this thread is to focus on built-in MATLAB functionality.)
11 Comments
For years, I was numbering my matrices manually in a most tedious fashion , like -
A1=1;
A2=2;
A3=3;
-
-
-
A1000=1000;
Then, Aha! I discovered EVAL and it got so much simpler!!!
for i=1:1000
is=num2str(i);
eval(['A' is '=' is]);
end
I think features like ComparisonMethod are easy to miss. They get added to existing functionality, extending those tools in many useful ways. But unless we carefully read the release notes for each release (something I am often lax to do) then we never see these nice additions to the language. The answer of course is to read the release notes.
xline() and yline() were added in R2018b. In older versions, there was refline (though I guess that was Statistics toolbox)
Great topic!!
I remember discovering the "ComparisonMethod" option in functions like max, min, issorted, and others. It's really useful when you're only concerned with magnitudes and not signs.
For example,
a = [4 2 -5 -3 1]
[m, n] = max(a,[],ComparisonMethod='abs')
m =
-5
n =
3
It save users from thinking about how to solve this by using abs() without losing the original sign of the max(abs()).
aAbs = abs(a);
[~, n] = max(aAbs)
m = a(n)
n =
3
m =
-5
>>