MATLAB: How to get the actual position of a plot or image in MATLAB

imshowinnerpositionMATLABplotboxaspectratio

I am trying to place two images next to each other, "pinning" one image to the other. However, even though the rectangles which define the axes objects are adjacent, the two images are not actually touching.
The following illustrates the issue:
figure;
set(gcf,'units','pixels','position',[40 44 1105 546])
% testimage :e.g. image of 20X10 pixels in size
testimage = rand(20,10);
%set axes to be adjacent
handles.mainaxes = axes('units','pixels','position',[200 200 100 100],'visible','on');
handles.secaxes = axes('units','pixels','position',[100 200 100 100],'visible','on');
%display image
axes(handles.mainaxes);
imshow(testimage);

Best Answer

The ability to get the actual position of a plot or image is not available in MATLAB. The plot area will always lie within the axes object; however it may not fill the entire axes object. This happens whenever the aspect ratio of a plot is changed such as by using the AXIS SQUARE or AXIS IMAGE commands or when displaying an image using IMSHOW. Instead, the plot or image is centered in the axis object and the axes position property does not reflect the actual position of the plot or image.
To work around this issue, modify the axes object's height to width ratio to match the plot's aspect ratio. This can be accomplished by adding the following code to the program above:
% Get the new aspect ratio data
aspect = get(handles.mainaxes,'PlotBoxAspectRatio');
% Change axes Units property (this only works with non-normalized units)
set(handles.mainaxes,'Units','pixels');
% Get and update the axes width to match the plot aspect ratio.
pos = get(handles.mainaxes,'Position');
pos(3) = aspect(1)/aspect(2)*pos(4);
set(handles.mainaxes,'Position',pos);