Matlab平铺所有打开的绘图窗口
直接上代码:
这是跟ChatGPT battle了多轮之后的结果(但是还得手动改掉一部分内容)
1function arrangefigs(yUseRatio, mode)
2
3% arrangefigs - 自动排列屏幕上的绘图窗口
4% 输入:
5% yUseRatio - 屏幕Y方向占据的比例,默认为0.95
6% mode - 指定为1时,横向排列窗口
7%
8
9% Get screen size
10screenSize = get(0, 'ScreenSize');
11screenWidth = screenSize(3);
12screenHeight = screenSize(4);
13
14if nargin < 2
15 mode = 0;
16end
17
18if nargin < 1
19 yUseRatio = 0.95;
20else
21 assert(yUseRatio > 0 && yUseRatio <= 1, "yUseRatio需要在(0, 1]范围内")
22end
23
24% Get handles to all open figures
25figures = flip(findobj('Type', 'figure'));
26numFigures = length(figures);
27
28% Retrieve original sizes of the figures
29originalSizes = zeros(numFigures, 4);
30
31for i = 1:numFigures
32 originalSizes(i, :) = get(figures(i), 'OuterPosition');
33end
34
35% Calculate the number of columns and rows based on the number of figures
36averageFigureWidth = mean(originalSizes(:, 3));
37averageFigureHeight = mean(originalSizes(:, 4));
38if mode == 1
39 numRows = 1;
40else
41 numRows = max(1, floor(screenHeight * yUseRatio / averageFigureHeight));
42end
43numColumns = max(1, ceil(numFigures / numRows));
44
45% if (numColumns * averageFigureWidth > screenWidth)
46% numRows = numRows + 1;
47% numColumns = max(1, ceil(numFigures / numRows));
48% end
49
50% Calculate spacing between figures
51spacingX = max((screenWidth - numColumns * averageFigureWidth) / (numColumns + 1), 0);
52spacingY = max((screenHeight * yUseRatio - numRows * averageFigureHeight) / (numRows + 1), 0);
53
54% Set initial position
55x = spacingX; % initial x-coordinate
56y = screenHeight - spacingY - averageFigureHeight; % initial y-coordinate
57
58% Iterate through figures and move each figure to the grid position
59for i = 1:numFigures
60 % Retrieve original size of the current figure
61 originalSize = originalSizes(i, :);
62
63 % Customize the position of each figure
64 set(figures(i), 'OuterPosition', [x, y, originalSize(3), originalSize(4)]);
65
66 % Bring the figure to the front
67 figure(figures(i));
68
69 % Update position for the next figure
70 x = x + min(originalSize(3) + spacingX, (screenWidth - averageFigureWidth) / (numColumns - 1));
71
72 % Check if the next column needs to start in a new row
73 if mod(i, numColumns) == 0
74 x = spacingX;
75 y = y - min(spacingY + averageFigureHeight, screenHeight / numRows);
76 end
77end
78end
79