How can I convert the following loop operation into vectorization?

1 view (last 30 days)
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 Comments
vinjamoori vikas
vinjamoori vikas on 19 Aug 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 on 19 Aug 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

Sign in to comment.

Answers (1)

DGM
DGM on 19 Aug 2021
Edited: DGM on 19 Aug 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).

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!