Effacer les filtres
Effacer les filtres

How can I convert the following loop operation into vectorization?

1 vue (au cours des 30 derniers jours)
vinjamoori vikas
vinjamoori vikas le 19 Août 2021
Modifié(e) : DGM le 19 Août 2021
S is the 3-dimensional array of size 64X36X36
d_E1=[];
for d=1:length(th_2)%Page selection
for c=1:length(th_3)%column celection
for i=1:size(S,1)-1%row selection
for j=i+1:size(S,1)
d_E=norm(S(i,c,d)-S(j,c,d));
d_E1=[d_E1 d_E];
end
end
end
end
%creating 3-dimensional PEP arra
d_E_new=reshape(d_E1,nchoosek(size(S_sum1,1),2),length(th_3),length(th_2));
  2 commentaires
vinjamoori vikas
vinjamoori vikas le 19 Août 2021
Sorry, I have not mentioned about lengths.
take
length(th_2)=36(3rd dimension of the matrix)
length(th_3)=36(2nd dimension of the matrix)
darova
darova le 19 Août 2021
I think vectorization version can be too complicated. I suggest you to preallocate d_E1 variable (calculate the size)
I also don't understand why do you norm function if oyu just substracting numbers
norm(2-1)
ans = 1
norm(5-3)
ans = 2

Connectez-vous pour commenter.

Réponses (1)

DGM
DGM le 19 Août 2021
Modifié(e) : DGM le 19 Août 2021
I'm not sure why you're using norm() on scalars. Abs() has the same effect.
% test array/size
N = 4; % rows/cols
D = 4; % pages
S = repmat(magic(N),[1 1 1 D]);
% original structure
E1=[];
for d=1:D%Page selection
for c=1:N%column celection
for i=1:N-1%row selection
for j=i+1:N
E=norm(S(i,c,d)-S(j,c,d));
E1=[E1 E];
end
end
end
end
% somewhat simplified
E3=[];
for i=1:N-1 % row selection
E = abs(S(i,:,:)-S(i+1:N,:,:));
E3 = [E3; E];
end
E3 = reshape(E3,1,[]);
immse(E1,E3) % they should be identical
ans = 0
I didn't really think it would be that much faster, but for a 20x20x20 array, the revised code executes in less than 1/1000th the time (on my hardware/version/environment).

Catégories

En savoir plus sur Creating and Concatenating Matrices 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!

Translated by