【问题标题】:Matrix dimensions must agree, Index exceeds matrix dimensions矩阵维度必须一致,索引超出矩阵维度
【发布时间】:2017-01-24 08:53:17
【问题描述】:

我有以下代码用于定位一些子图:

fig = figure;
fig.Units = 'centimeters';
fig.Position(3:4) = [25  25];
plotPositions = [ 3, 21,  7,  7;
                 12, 21,  7,  7;  
                ];
nPlots=length(plotPositions);  % shorthand variable for convenience
hAx=zeros(nPlots,1);           % preallocate array for axes/subplot handles
for i = 1:length(plotPositions)
    plotHandle = subplot(3, 2, i);
    plotHandle.Units = 'centimeters';
    plotHandle.Position = plotPositions(i,:);
    hAx(i)=subplot(3, 2, i);  
    axis(hAx(i),[ -300 300 0 150]); %
end

如果我使用

plotPositions = [ 3, 21,  7,  7;
                 12, 21,  7,  7;
                  3, 12,  7,  7;
                 12, 12,  7,  7;
                  3,  3,  7,  7;
                 12,  3,  7,  7];

它有效,但如果使用

plotPositions = [ 3, 21,  7,  7;
                 12, 21,  7,  7;  
                ];

它不起作用,我收到错误消息:

Matrix dimensions must agree.

Index exceeds matrix dimensions.

发生了什么事?

【问题讨论】:

    标签: matlab matrix indexing plot matlab-figure


    【解决方案1】:

    您不应该使用函数length,而是使用函数size(...,1) 来计算plotPositions 的行数。 length 实际上是max(size(vec)),在“工作”情况下是6(正确的行数)和4列数 ) 在非工作中。

    因此,在第 2nd 种情况下,您实际上是在尝试访问“不存在”的行,因此 MATLAB 抱怨......

    【讨论】:

    • @Mueller 不客气。也可以进一步解释here