This is mainly a personal preference unless you need to write code which will work in pre-HG2 versions of MATLAB (before R2014b) in which case you would need to use set
and get
to maintain backwards compatibility.
Here are a few other advantages to using set
and get
methods:
Manipulation of Multiple Objects Simultaneously
You can have an array of objects or handles and change a property on all of them simultaneously
ax(1) = subplot(1,2,1);
ax(2) = subplot(1,2,2);
% Change the font weight of both axes object to be the same
set(ax, 'FontWeight', 'bold')
% Change the font weight to be different for each
set(ax, {'FontWeight'}, {'bold'; 'normal'})
You can do something similar with dot notation but I think it's a little less readable
[ax.FontWeight] = deal('bold');
Changing Multiple Properties Simultaneously
You can, in one statement, change the values of multiple properties which I think can help with readability and keep your code concise.
set(ax, 'FontSize', 20, 'FontWeight', 'bold', 'FontName', 'arial')
As pointed out in the comments by @Hoki, this is particularly important if you are updating properties that are inter-dependent. For example modifying the XData
and YData
of a plot where they both need to be the same size.
So this:
hplot = plot(1, 1);
set(hplot, 'XData', rand(10, 1), 'YData', rand(10, 1))
Instead of this:
hplot = plot(1, 1);
set(hplot, 'XData', rand(10, 1))
% Plot won't render here
set(hplot, 'YData', rand(10, 1))
% Plot will be able to render
Programmatically Get Possible Values
With dot notation, you can use tab completion to get a list of possible values; however, you can do this programmatically with set
by simply not providing a value.
possible = set(axes, 'FontWeight')
% 'normal'
% 'bold'
Shortened and Case-Insensitive Properties
I don't recommend using these next two, but they are possible with set
and get
.
With the set
and get
methods you don't have to provide an entire properties name, just enough letters that it's unique.
set(ax, 'FontW', 'bold')
Also when using set
and get
, the property name is case insensitive
set(ax, 'fontweight', 'bold')