Canonical method for setting graphics properties in MATLAB 2014b?

1 view (last 30 days)
Now that graphics handles are objects, I'm curious what folks would consider to be the canonical method for setting graphics properties. Here is an example from a recent answer of mine on this forum:
% Some data
x = 0:pi/10:pi;
y = sin(x);
% Create figure
figure
plot(x,y,x,2*y)
hL = legend({'1','2'});
% Get current position (which I used to keep overall size the same)
currentLegendPosition = hL.Position;
% Define new position
newLegendPosition = [0.5 0.5 currentLegendPosition([3 4])];
% Method 1 for setting new position
hL.Position = newLegendPosition;
% Method 2 for setting new position
set(hL,'Position',newLegendPosition)
The second method (pun intended) strikes me as the preferred one, because it actually uses a method ("set") of the object class, but I am curious about other opinions. I don't have much experience in object-oriented languages.

Accepted Answer

Mike Garrity
Mike Garrity on 9 Oct 2014
If you're writing code which only needs to run in R2014b or later, then the first form (aka "dot notation") is preferred. There are a couple of reasons for this.
  • It is faster.
  • Tab completion is a bit more robust when you're using it.
  • It also makes your code easier to read.
There are two caveats (aren't there always?). It currently doesn't work for arrays of graphics objects or with functions which return graphics objects. So these two cases don't yet work.
h = plot(magic(6))
h.LineWidth = 6
gca.XLim = [10 20]
You should continue to use "set" for these two cases, although I will usually write the second like so:
ax = gca
ax.XLim = [10 20]
And, of course, if your code needs to run in earlier versions, you should use "set".

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!