保存带有子图的图形而不填充白色边距

Saving a figure with subplots without padding white margins

以下代码删除了 MATLAB 中一堆子图周围的填充。我在 here 的评论中找到了它。

x = -pi:.1:pi;
h=figure;
subplot(2,1,1)
plot(x,sin(x))
subplot(2,1,2)
plot(x,cos(x))

a = findall(h,'type','axes');
for i=1:length(a)
    ti = get(a(i),'TightInset');
    op = get(a(i),'OuterPosition');
    set(a(i),'Position',[op(1)+ti(1) op(2)+ti(2) op(3)-ti(3)-ti(1) op(4)-ti(4)-ti(2)]);
end

我不知道他的其余代码在做什么。但是,这么多代码就完成了工作(认为不是很准确)。

现在,我的问题是我不想在显示时删除填充,因为它变得很难看。我只想在使用命令 printsaveas 保存时删除填充。有什么办法吗?

我会给你一个快速修复。它有效,但不是很优雅:

x = -pi:.1:pi;
h1 = figure;
subplot(2,1,1)
plot(x,sin(x))
subplot(2,1,2)
plot(x,cos(x))

%% Save figure

x = -pi:.1:pi;
h2 = figure('visible','off');
subplot(2,1,1)
plot(x,sin(x))
subplot(2,1,2)
plot(x,cos(x))

a = findall(h2,'type','axes');
for i=1:length(a)
    ti = get(a(i),'TightInset');
    op = get(a(i),'OuterPosition');
    set(a(i),'Position',[op(1)+ti(1) op(2)+ti(2) op(3)-ti(3)-ti(1) op(4)-ti(4)-ti(2)]);
end
saveas(h2,'newout','fig')