MATLAB: How to print a figure from the command line with the aspect ratio fixed while filling the page

MATLAB

I would like to print a figure as large as I can without "stretching" (with a fixed aspect ratio) from the command line.

Best Answer

The following code resizes and repositions the figure on the paper so that it is as large as possible with a fixed aspect ratio
h=gcf;
pos = get(h,'Position');
aspect = pos(3)/pos(4) %width/height

set(h,'PaperOrientation','landscape');
set(h,'PaperPositionMode','manual');
set(h,'PaperUnits','normalized');
s = get(h,'PaperSize');
paperaspect = s(1)/s(2); %width/height
if(aspect > paperaspect)
set(h,'PaperPosition', [0 .5-.5/aspect 1 1/aspect]);
elseif(aspect < 1)
set(h,'PaperPosition', [.5-.5*aspect 0 aspect 1]);
else
set(h,'PaperPosition', [0 0 1 1]);
end
print(h, '-dpdf', 'test1.pdf');
set(h,'PaperUnits', 'inches');
Related Question