필터 지우기
필터 지우기

How can I convert the following loop operation into vectorization?

조회 수: 2 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by