Reputation: 20405
I am trying to set the XTick
for each of my subplot. After reading the MATLAB documentation here, I decided to do the following, but it is not working.
MWE
subplot(2, 1, 1);
gca.XTick = [0, 6, 12, 18, 24];
subplot(2, 1, 2);
gca.XTick = [0, 6, 12, 18, 24];
My MATLAB version is
>> version
ans =
8.4.0.150421 (R2014b)
Upvotes: 4
Views: 3489
Reputation: 23908
You can't use gca
directly as though it were a handle reference on the left hand side of an assignment operation. You can use either the set(gca, ...)
syntax or ax = gca; ax.XTick ...
, but only if you avoid the gca.Whatever = ...
syntax, which will break gca
in the workspace you do it in due to identifier shadowing.
The syntax
gca.XTick = [0, 6, 12, 18, 24];
will not do what you want. Instead of calling the gca()
function, this creates a new local variable called gca
and populates it with a struct that has a field named XTick
. Not only does this not set the ticks in the plot, but the new variable masks the gca
function, so subsequent calls to gca
in the same workspace will not work until a clear
or a restart is done (they'll just access the local struct fields instead).
Using a temporary variable like this
ax = gca;
ax.XTick = [0, 6, 12, 18, 24];
should work, as long as you have not already done a gca.XTick = ...
assignment in that workspace, or do one anywhere in the same function.
This is an unfortunate quirk of how Matlab's take on the "uniform access principle" works: you can call an argumentless function or method without parentheses (like set(gca, 'XTick', ...)
), but only if you do not also use that same identifier as an lvalue in an assignment statement in the same function, which causes the parser to identify it as a local variable instead of a function call.
In short, don't put gca
on the left hand side of a =
assignment operation, and it should work.
You can see this in action using whos
or which
. Throw the code in a function so it gets a clean workspace and use which
to see what gca
resolves to.
function darnit_gca()
disp('gca is:');
which gca
subplot(2, 1, 1);
gca.XTick = [0, 6, 12, 18, 24];
subplot(2, 1, 2);
gca.XTick = [0, 6, 12, 18, 24];
disp('now gca is:');
which gca
When you run darnit_gca
, you can see the resolution of gca
change once you use it as an lvalue.
>> darnit_gca
gca is:
built-in (/Applications/MATLAB_R2014b.app/toolbox/matlab/graphics/gca)
now gca is:
gca is a variable.
Upvotes: 6