how to vectorize nested for loops

조회 수: 1 (최근 30일)
AliHg
AliHg 2019년 9월 10일
댓글: Rik 2019년 9월 17일
Hello everyone
I want to vectorize the following code to reduce operation time. Can you guys help me out?
thanks
% X is a double matrix
s=size(X);
RepSol=repmat(X,2,2);
% Y is a binary matrix
Y=repmat(Y,2,2);
% Preallocation
p=zeros(s);
for m=1:s(1)
for n=1:s(2)
for i=1:s(1)
for j=1:s(2)
if RepSol(i,j)==RepSol(m+i-1,n+j-1)
p(m,n)=p(m,n)+Y(i,j)*Y(m+i-1,n+j-1);
end
end
end
end
end

답변 (2개)

darova
darova 2019년 9월 10일
IS it correct?
for m=1:s(1)
for n=1:s(2)
cond = RepSol(1:s(1),1:s(2)) == RepSol((1:s(1))+m-1,(1:s(2))+n-1);
% cond = X - RepSol((1:s(1))+m-1,(1:s(2))+n-1);
P = Y(1:s(1),1:s(2)) .* Y((1:s(1))+m-1,(1:s(2))+n-1);
res = cond .* P;
p(m,n) = sum(res(:));
end
end
  댓글 수: 4
AliHg
AliHg 2019년 9월 11일
편집: AliHg 2019년 9월 11일
Dear darova
Thank you for your prompt response. Your code produce the same answer as mine, yet it does not improve the speeding as much. The reason the speed is incredibly important to me is that this code is a function of a much larger code and it needs to be computed more than 30.000 times; hence I need it to be as simple as possible. My own solution for improving the speed was to vectorize the nested "for" loops and avoid using Repmat cause according to MATLAB Profiler, the "if" part in my code consumes most of the runtime.
I am wondering if it is feasible to vectorize the two remaining "for" loops in your code.
AliHg
AliHg 2019년 9월 11일
Dear Bob
Thank you for putting your time and energy into my question. As I mentioned in my previous comment, derova’s code produces identical answers but does not improve the speed.
To answer to your question I have to say in my knowledge there is no function in MATLAB that does the same thing. Also, I cannot go through details because the code is somehow simple and hard to explain at the same time.

댓글을 달려면 로그인하십시오.


AliHg
AliHg 2019년 9월 17일
Can anyone suggest anything regarding boosting my code? I have tried everything but nothing seems to workout.
  댓글 수: 4
darova
darova 2019년 9월 17일
Unfortunately is explains nothing
The script does the follwoing if i understood correctly:
img1 - Copy - Copy.png img1 - Copy - Copy (2).png img1 - Copy - Copy (3).png
Rik
Rik 2019년 9월 17일
I agree with darova that your explanation is minimal. Please edit your question, adding what you're trying to achieve. Maybe your problem can be solved with a well-chosen convolution, but with the current level of detail it is impossible to give you a better solution than you already have been given.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by