Simpler Subplots: Converting Grid Coordinates to Axes Position

When you're working with a subplot matrix where each row is some new analysis, using the standard "position" or p input to MATLAB subplot is not intuitive. Rather, you want to specify your subplot by rows and columns. This tiny function, prc, does that conversion.

function p = prc(cols,rc)
% rc = desired [row,col] position of subplot
p = (rc(1) * cols) - (cols - rc(2));

The function requires the number of columns in your figure (cols) and the two-element position of your desired subplot (rc) given as an array in the format, [row, col]. Here's an example for using Subplot 8:

rows = 3;
cols = 4;
figure;
subplot(rows, cols, prc(cols, [2, 4]));
simplerSubplots_MATLAB.png

Supplemental

The figure above was generated with the following code.

rows = 3;
cols = 4;
figure;

for iRow = 1:rows
    for iCol = 1:cols
        subplot(rows,cols,prc(cols,[iRow iCol]));
        title(['Subplot ',num2str(prc(cols,[iRow iCol]))],'fontSize',14);
        text(0.5,0.5,[num2str(iRow),', ',num2str(iCol)],...
            'HorizontalAlignment','center','fontsize',14);
    end
end