matlab中的子图问题

matlab中的子图问题,matlab,plot,subplot,Matlab,Plot,Subplot,我在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

我在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是新手


谢谢

子批中的第三个参数不能超过子批的总数。例如,当您使用子批(5,4,…)时,这意味着总共有5*4=20个子批,因此第三个参数不能是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
...

之所以会出现此错误,是因为
子地块
希望得到5x4=20个子地块,而您启动循环告诉它将地块定位在第21个位置,但这不起作用

您只需在调用
子批
时从索引中减去20即可确保您在正确的范围内

例如

屈服:


当您使用
子批次(a、b、idx)
时,idx在[1 a*b]范围内可用,其中a是图中的行数,b是列数。很高兴这有帮助。你能接受这个答案吗?
subplot(5,4,ii-20)