how to vectorize nested for loops
이전 댓글 표시
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
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
Bob Thompson
2019년 9월 10일
cond = RepSol(1:s(1),1:s(2)) == RepSol((1:s(1))+m-1,(1:s(2))+n-1);
A couple of things:
RepSol(1:s(1),1:s(2))
This is just the entirety of RepSol, you shouldn't need to index it
RepSol((1:s(1))+m-1,(1:s(2))+n-1)
Your indexing here doesn't make sense. (1:s(1)) is just calling all rows, but then you're trying to adjust that range to +m-1. So, suppose you have ten rows, and you are looking at m = 5, then you are saying you want to look at rows 5:15, which isn't possible because you only have 10 rows.
Unfortunately, I don't have a way to solve your problem off the top of my head, but it might help us come up with a solution if you explain what you're trying to do with your loops. There might be a command which does it already.
darova
2019년 9월 10일
s(1) and s(2) are size of RepSol before repmat (two times less)
s=size(X);
RepSol=repmat(X,2,2);
AliHg
2019년 9월 11일
AliHg
2019년 9월 17일
0 개 추천
댓글 수: 4
darova
2019년 9월 17일
Can you tell something more about your problem? What are yuo working on now?
Maybe there is some solution
AliHg
2019년 9월 17일
darova
2019년 9월 17일
Unfortunately is explains nothing
The script does the follwoing if i understood correctly:
.png)
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.
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!