How can I convert the following loop operation into vectorization?

1 回表示 (過去 30 日間)
vinjamoori vikas
vinjamoori vikas 2021 年 8 月 19 日
編集済み: DGM 2021 年 8 月 19 日
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 件のコメント
vinjamoori vikas
vinjamoori vikas 2021 年 8 月 19 日
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 2021 年 8 月 19 日
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

サインインしてコメントする。

回答 (1 件)

DGM
DGM 2021 年 8 月 19 日
編集済み: DGM 2021 年 8 月 19 日
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).

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by