Effacer les filtres
Effacer les filtres

Vectorization for Two Nested for-loops

35 vues (au cours des 30 derniers jours)
Mohammed
Mohammed le 1 Juil 2024 à 10:33
Modifié(e) : Stephen23 le 1 Juil 2024 à 13:38
Hello all,
I'm trying to vectorize some operation between two 2D matrices, A and B. Basically, the process is multiplying every row verctor from matrix B by every vector from matrix A and store the value in matrix C. The correct non-vectorized code looks as follows:
A = [2 3 4; 5 2 1; 1 4 3];
B = [3 4 4; 4 2 1; 4 4 1];
C = zeros(3,3); % Initializing C
for ii=1:size(A,1)
for jj=1:size(B,1)
AA = A(ii,:);
BB = transpose(B(jj,:));
C(jj,ii) = sum(BB*AA, 'all')
end
end
C
The resultant C should looks as:
C =
99 88 88
63 56 56
81 72 72
Can I get help here?
Thanks!

Réponses (2)

Tomoaki Takagi
Tomoaki Takagi le 1 Juil 2024 à 11:49
Try:
A = [2 3 4; 5 2 1; 1 4 3];
B = [3 4 4; 4 2 1; 4 4 1];
C = repmat(A,3).*repelem(B,3,3);
C = reshape(sum(C,2),3,3)'

Stephen23
Stephen23 le 1 Juil 2024 à 13:35
Modifié(e) : Stephen23 le 1 Juil 2024 à 13:38
Without creating multiple copies of data in memory:
A = [2 3 4; 5 2 1; 1 4 3];
B = [3 4 4; 4 2 1; 4 4 1];
C = sum(permute(A,[3,1,2,4]).*permute(B,[1,3,4,2]),3:4)
C = 3x3
99 88 88 63 56 56 81 72 72
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
The same basic approach, more verbose but possibly more efficient:
As = size(A);
Bs = size(B);
C = sum(reshape(A,[1,As]).*reshape(B,[Bs(1),1,1,Bs(2)]),3:4)
C = 3x3
99 88 88 63 56 56 81 72 72
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by