MATLAB: Unable to link x-axis in subplot

linkaxissubplot

I can't seem to get linkaxis to work (code is below, with small datasets attached). I am trying to get the subplots to line up, such that visually the x-axis is has the same range and width for both subplots.
Here is my code:
ax1 = subplot(2,1,1);
scatter(x1, y1)
box on
grid on
axis equal
xlims = get(gca, 'XLim')
ax = gca;
ax.XRuler.Exponent = 0;
ax.YRuler.Exponent = 0;
xlims = get(gca, 'XLim')
ax2 = subplot(2,1,2);
scatter(x1, y1)
xlim(xlims)
box on
grid on
ax = gca;
ax.XRuler.Exponent = 0;
linkaxes([ax1,ax2],'x')
And here is what the figure looks like:
I also tried:
% adding this to the first subplot:
xlims = get(gca, 'XLim')
positioning = get(gca,'position');
% adding this to the second subplot:
xlim(xlims)
set(gca, 'position', [positioning(1) positioning(2)/5 positioning(3) positioning(4)]) %x y width height

Best Answer

Example
clc,clear
x = linspace(0,10);
y1 = sin(x)./x;
y2 = sin(x)/2;
ax(1) = subplot(2,1,1);
plot(x,y1)
ax(2) = subplot(2,1,2);
plot(x,y2);
set(ax,'Xlim',[2 5],'Box','on')
set(ax,'xgrid','on','ygrid','on')
axis(ax,'equal')