Pietro Z.
Pietro Z.

Reputation: 531

Vectorise for-loop

I need to replace this for-loop with better code:

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

where:

The for-loop is working, but is too slow.

example of matrix:

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

Upvotes: 0

Views: 38

Answers (1)

user2271770
user2271770

Reputation:

I think this should work:

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

Test:

    %% 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(:)));

Upvotes: 2

Related Questions