矢量for循环

时间:2015-10-12 15:10:12

标签: matlab matrix vectorization

我需要用更好的代码替换这个for - 循环:

for g=1:length(B)
    C(g,:)=[A(B(g,1),:),A(B(g,2),:),A(B(g,3),:)];
end

其中:

  • A N a -by- 2 矩阵,
  • B N b -by- 3 矩阵和
  • C N b -by- 6 矩阵。

for - 循环正在运行,但速度太慢。

矩阵的例子:

A =

 1     2
 1     3
 1     4
 1     5
 1     6
 2     3
 2     4
 2     5
 2     6

B =

 1     2     3
 1     2     4
 1     2     5
 1     2     6
 1     2     7
 1     2     8
 1     2     9

C =

 1     2     1     3     1     4
 1     2     1     3     1     5
 1     2     1     3     1     6
 1     2     1     3     2     3
 1     2     1     3     2     4
 1     2     1     3     2     5
 1     2     1     3     2     6

1 个答案:

答案 0 :(得分:2)

我认为这应该有效:

    C1 = reshape(A(B.',:).', 6, []).';

测试:

    %% Build minimal case
    A = reshape(1:10, 5, 2);
    B = randi(size(A,1), 7, 3);

    %% Original code
    for g=1:length(B)
        C(g,:)=[A(B(g,1),:),A(B(g,2),:),A(B(g,3),:)];
    end

    %% Proposed code
    C1 = reshape(A(B.',:).', 6, []).';

    %% Test
    disp(all(C1(:) == C(:)));