Vectorized nD diag loop
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Javier Fernandez
il 5 Lug 2022
Commentato: Javier Fernandez
il 5 Lug 2022
Hello everyone,
I have the following loop which I would want to have vectorized.
I know the diag() command cannot be used in nD arrays (n>2), so is there an alternative way to vectorize the loop?
n = 10; m = 15;
A = rand(4,n,m);
for i = 1:n
for j = 1:m
B(:,:,i,j) = diag(A(:,i,j));
end
end
Thanks in advance!
0 Commenti
Risposta accettata
Chunru
il 5 Lug 2022
n = 400; m = 500;
A = rand(4,n,m);
B = zeros(4,4,n,m); % initialize to speed up
tic
for i = 1:n
for j = 1:m
B(:,:,i,j) = diag(A(:,i,j));
end
end
toc
% Vectorized
tic
C = zeros(4*4,n*m);
C(1:5:16, :) = A(1:4, :);
C =reshape(C, [4, 4, n, m]);
toc
isequal(B, C)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!