Circshift matrix by different amount without for loop
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Javier Agustin Romero
le 29 Mar 2019
Modifié(e) : Javier Agustin Romero
le 30 Mar 2019
Hello everyone. I have this 3 dimensional matrix called spectrums and I want to shift the 3rd dimension by different amounts given by vector shifts. Is there a way to do this without using a for loop? something like
shifted_spectrums=arrayfun(@(k) circshift(spectrums(:,:,k),shifts(2:end),2),spectrums);
but a solution that actualy works :P
PS: 3rd dimension of spectrums has 22 elements and shifts has 23 elements, that's why the 2:end.
1 commentaire
Jan
le 29 Mar 2019
Modifié(e) : Jan
le 29 Mar 2019
What is the class and contents of shifts(2:end)? What is not "actually working"?
We cannot guess these details.
A for loop is faster than arrayfun in general. So please mention, why you want to avoid it.
Is this the loop version?
shifted_spectrums = zeros(size(spectrums));
for k = 1:size(spectrums, 3)
shifted_spectrums(:, :, k) = circshift( ...
spectrum(:, :, k), shifts(k+1), 2);
end
Réponse acceptée
Javier Agustin Romero
le 29 Mar 2019
Modifié(e) : Javier Agustin Romero
le 29 Mar 2019
Plus de réponses (1)
Jan
le 29 Mar 2019
Modifié(e) : Jan
le 29 Mar 2019
Try:
n = 8192;
spectrums = rand(512, n, 22);
shifts = randi(n, 1, 22);
tic
s1 = cell2mat(arrayfun(@(k) ...
circshift(spectrums(:,:,k), shifts(k), 2),1:22,'uni',0));
toc
tic;
s2 = zeros(size(spectrums));
for k = 1:22
s2(:,:,k)=circshift(spectrums(:,:,k), shifts(k), 2);
end
toc
For n=2000 I get:
arrayfun: 0.22sec
loop: 0.17sec
3 commentaires
Jan
le 29 Mar 2019
Modifié(e) : Jan
le 30 Mar 2019
i7-3770 3.4GHz, 16 GB RAM, n = 8192:
R2009b:
Elapsed time is 2.660240 seconds.
Elapsed time is 2.062384 seconds.
R2016b:
Elapsed time is 2.613608 seconds.
Elapsed time is 2.292270 seconds.
R2018b:
Elapsed time is 2.682782 seconds.
Elapsed time is 1.207014 seconds. ! Nice !
Javier Agustin Romero
le 30 Mar 2019
Modifié(e) : Javier Agustin Romero
le 30 Mar 2019
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!