matlab中的子图问题

Subplot problems in matlab

我正在用 matlab 解决一个问题,要求我绘制 100 年的年龄分布,需要 100 个图。我希望创建 5 个单独的地块,每个地块有 20 个子地块,总共 100 个地块。我似乎无法通过前 20 个地块而不会在我的子地块命令中出现错误。

这是代码的初始部分:

>> %initial age distribution
x0=[10;10;10];
%projection matrix
M=[0 4 3; 0.6 0 0; 0 0.25 0];

%calculate the total population size and age distribution for the first 100     years
X=zeros(3, 100);
X(:,1) = x0;
for kk = 2:100
X(:,kk) = M*X(:,kk-1);
end

%we need to double the population to account for males, assuming that   population is ½ males and ½ females

X=2*X

我最初的计划是创建一个 10x10 的子图,但它看起来很糟糕,但这是我生成的代码。

for ii = 1:100
subplot(10,10,ii)
set(gca,'FontSize',12)
barh(log10(X(:,ii)));
set(gca,'YTickLabel',{'Y1' 'Y2' 'Y3'})
xlabel('log(popn.)')
title(['Y' ,num2str(ii)])
axis([-1 25 0.5 3.5])
end

所以我决定以 20 个为一组进行。

这是我拥有的:

for ii = 1:20
subplot(5,4,ii)
set(gca,'FontSize',12)
barh(log10(X(:,ii)));
set(gca,'YTickLabel',{'Y1' 'Y2' 'Y3'})
xlabel('log10(population)')
title(['Y' ,num2str(ii)])
axis([-1 25 0.5 3.5])
end

当我尝试从 21 到 40 时,出现如下错误:

for ii = 21:40
subplot(5,4,ii)
set(gca,'FontSize',12)
barh(log10(X(:,ii)));
set(gca,'YTickLabel',{'Y1' 'Y2' 'Y3'})
xlabel('log10(population)')
title(['Y' ,num2str(ii)])
axis([-1 25 0.5 3.5])
end
Error using subplot (line 280)
Index exceeds number of subplots.

我需要重复 21-40、41-60、61-80 和 81-100。任何帮助将不胜感激。我是 matlab 新手。

谢谢!

子图中的第三个参数不能超过子图的总数。比如当你使用subplot(5, 4, ...)时,表示总共会有5*4 = 20个subplot,所以第三个参数不能是21.

因此您需要使用figure 命令创建一个新图形,然后创建接下来的 20 个子图。最后,你会得到5个不同的数字。

因此您的代码将如下所示:

figure(1);    % First figure window
for ii = 1:20
    subplot(5,4,ii)    % create first 20 subplots
    set(gca,'FontSize',12)
    barh(log10(X(:,ii)));
    set(gca,'YTickLabel',{'Y1' 'Y2' 'Y3'})
    xlabel('log10(population)')
    title(['Y' ,num2str(ii)])
    axis([-1 25 0.5 3.5])
end
figure(2);    % second figure window
for ii = 21:40
    subplot(5,4,ii-20)    % create next 20 subplots
    set(gca,'FontSize',12)
    barh(log10(X(:,ii)));
    set(gca,'YTickLabel',{'Y1' 'Y2' 'Y3'})
    xlabel('log10(population)')
    title(['Y' ,num2str(ii)])
    axis([-1 25 0.5 3.5])
end
...

你得到错误是因为 subplot 期望得到 5x4 = 20 个子图,而你开始循环告诉它把图定位在第 21 个位置,这是行不通的。

您可以简单地从调用 subplot 的索引中减去 20,以确保您在正确的范围内。

例如

subplot(5,4,ii-20)

产量: