For循环继续经过设定的终点(matlab)

For loop continuing past set end point (matlab)

我有一个矩阵数组,它们的长度都不同。我想比较矩阵 1 中每个项目与矩阵 2 中项目的距离,依此类推。我在下面编写的 for 循环运行良好,除非它到达长度为 2 的矩阵。循环继续到 xx = 3,然后调用错误(“位置 1 中的索引超出数组边界。索引不得超过 2。” ) 因为没有 current_mat(3,:)。为什么它只对长度为 2 的矩阵这样做?我是 matlab 的新手,如果这是一个简单的问题,我深表歉意。以下是一些玩具数据,它们给出了我在更大数据集上看到的相同错误。

matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}

for ii = 1:length(my_array)-1;
    current_mat = my_array{ii};
    compare_mat = my_array{ii+1};
    for xx = 1:length(current_mat);
        xx_info = current_mat(xx,:);
    end
end

问题是,当给定矩阵输入 length returns 时,矩阵的 最长 维度,而不是行数。在您的 matrix_3 的情况下,这是 3,尽管看起来您期望的是 2。因此 xx 从 1 变为 3,并且在第 11 行中,您尝试访问 [= 时不存在的行15=]。更好的办法是显式循环 m 维度。您可以使用 size 执行此操作,其中 returns 矩阵中的行数和列数:

matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}

for ii = 1:length(my_array)-1;
    current_mat = my_array{ii};
    compare_mat = my_array{ii+1};
    [m,n] = size(current_mat); % <-- use size here, not length
    for xx = 1:m;
        xx_info = current_mat(xx,:);
    end
end 

或者,如果您想查看这些列:

matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}

for ii = 1:length(my_array)-1;
    current_mat = my_array{ii};
    compare_mat = my_array{ii+1};
    [m,n] = size(current_mat); % <-- use size here, not length
    for xx = 1:n;
        xx_info = current_mat(:,xx);
    end
end 

此代码应该适合您。您没有具体指定列(或行)的长度作为行列式,

matrix_1 = ones(16,3);
matrix_2 = ones(14,3);
matrix_3 = ones(2,3);
matrix_4 = ones(10,3);
my_array = {matrix_1; matrix_2; matrix_3; matrix_4};

for ii = 1:length(my_array)-1
    current_mat = my_array{ii};
    compare_mat = my_array{ii+1};
    for xx = 1:size(current_mat,2)  % length of columns
        xx_info = current_mat(:,xx);  % Can compare across columns, since no of columns are consistent across multiple matrices
    end
end