【问题标题】:For loop continuing past set end point (matlab)For循环继续过去设定的终点(matlab)
【发布时间】:2022-01-12 22:06:21
【问题描述】:

我有一个长度不同的矩阵数组。我想比较矩阵 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。这是没用的。 numel 对于向量来说更快,或者明确说明您想要使用矩阵的大小:size(…, dim)

标签: matlab for-loop variable-length


【解决方案1】:

问题在于,当给定矩阵输入时,length 返回矩阵的最长维,而不是行数。在您的matrix_3 的情况下,这是 3,尽管您似乎期望 2。所以xx 从 1 变为 3,并且在第 11 行,您尝试访问在xx=3 时不存在的行。更好的做法是显式循环 m 维度。您可以使用size 执行此操作,它返回矩阵中的行数和列数:

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 

【讨论】:

  • 我意识到 OP 的内部 FOR 循环并没有真正进行比较,但是如果您跨行比较,它仍然会出错,不是吗?在这种情况下,OP 不应该跨列进行比较吗?
  • 我不会去读它。我不知道OP希望比较什么。我更新了答案以显示两种方式。
  • 这很好地解释了这个问题,但用笨拙的语法修复了它。 OP 需要将length(current_mat) 替换为size(current_mat,1)。如果只需要其中一个,则无需提取两个值。
【解决方案2】:

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

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

【讨论】:

  • 说 OP 使用“行的长度而不是 ... 列”是不正确的。正如我所指出的,length 返回最长维度的长度,而不是行数/列数。
  • 好的。很公平。我将删除我的答案,因为您已经涵盖了两者。以为我会在删除之前通知你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多