Canonical method for setting graphics properties in MATLAB 2014b?

1 次查看(过去 30 天)
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.

采纳的回答

Mike Garrity
Mike Garrity 2014-10-9
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".

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by