I need to make graphs in a software that are grouped in subplots. For this, I need to specify how many rows and how many columns of plots there will be. However, I do not know the total number of plots there will be.
I am therefore looking for a pseudo-code (or small algorithm) that would allow me to automatically define the number of rows and columns for those subplots.
Here is the objective of the problem:
- The number of rows and columns should be as close as possible from a perfect square.
Here are the constraints of the objective:
- The two numbers should be integers
- The number of rows should be larger than or equal to the number of columns
- The product of the two numbers should be larger than or equal to the number of subplots
I realize now that the problem resembles the maximization of the area of a four-sided figure with four right angles given its perimeter, with the perimeter being the number of subplots and the rows and columns being the length and width.
I am using Matlab, how would the code look like?
Here is what I have so far, but trying with in=7 and in=10 shows it is not correct:
function [rr,cc]=number_subplots(in)
sqrt_in=sqrt(in);
floor_in=floor(sqrt_in);
ceiling_in=ceil(sqrt_in);
[out]=sort([floor_in ceiling_in],'descend')
rr=out(1);
cc=out(2);
I figured it out: