MATLAB: Error using tiledlayout syntax instead of subplot when referencing axes handles

axes handleMATLABtiled layout

Hello, I am trying to use the newer tiledlayout feature rather than subplots as I want to adjust the padding round each subplot. However, I have functions that require an axes handle (ax1, ax2).
Normally I do this: (and it works fine):
ax1=subplot(4,8,[1,2,3,9,10,11],'Parent',f1);
myImshow1(app,IM,n, ax1); %my own imshow function
ax2=subplot(4,8,[4,5,6,7,8,13,14,15,16],'Parent',f1);
myImshow1(app,IM2,n, ax2);
I've tried using tilelayout syntax:
t=tiledlayout(f1,2,2,'TileSpacing','Compact');
ax1=gca;
myImshow1(app,IM,n, ax1)
nexttile(t); ax2=gca;
myImshow1(app,IM2,n, ax2);
But it complains

Best Answer

Be very careful about using gca, gcf, etc. in your code. I generally only use those when I'm experimenting in the Command Window.
Instead, call nexttile with an output argument. From its documentation page "ax = nexttile(___) returns the axes object." You can use the "Set Properties on the Axes" example on that documentation page as a model for your code, as it does something very similar to what you're trying to do.