Reputation: 531
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:
A
is an Na-by-2 matrix,B
is an Nb-by-3 matrix andC
is an Nb-by-6 matrix.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
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