Filter löschen
Filter löschen

How can I convert the following loop operation into vectorization?

2 Ansichten (letzte 30 Tage)
vinjamoori vikas
vinjamoori vikas am 19 Aug. 2021
Bearbeitet: DGM am 19 Aug. 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 Kommentare
vinjamoori vikas
vinjamoori vikas am 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 am 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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

DGM
DGM am 19 Aug. 2021
Bearbeitet: DGM am 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).

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by