How can I vectorize these for loops?

조회 수: 2 (최근 30일)
Budhvin Jayasinghe
Budhvin Jayasinghe 2020년 5월 28일
댓글: Budhvin Jayasinghe 2020년 5월 28일
Newbie here. I was wondering if there was a way to vectorize these for loops, or simply to change it to make it faster? Any help would be appreciated. Thank you!
m = zeros(50);
d = zeros(50);
for i = 1:size(m,1)
for n = 1:size(m,2)
try d(i,n) = sum(m(i-1:i+1,n-1:2:n+1),'all') + sum(m(i-1:2:i+1,n),'all');
catch, continue
end
end
end
What it does is scan the matrix positions immediately surrounding each matrix position being looped through and sums the values. It doesn't work at the edges or the corners, which is what the try, catch statement is for. Thanks again.
  댓글 수: 2
Stephen23
Stephen23 2020년 5월 28일
Use conv2:
x = [1,1,1;1,0,1;1,1,1];
d = conv2(m,x,'same');
Budhvin Jayasinghe
Budhvin Jayasinghe 2020년 5월 28일
Thank you.

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

채택된 답변

Mohammad Sami
Mohammad Sami 2020년 5월 28일
What you are trying to do is 2D convolution. There is a function conv2 that will allow you to do this.
m = ones(50);
filter = ones(3);
filter(2,2) = 0;
% 3x3 filter with excluding the center.
d = conv2(m,filter,'same');
  댓글 수: 1
Budhvin Jayasinghe
Budhvin Jayasinghe 2020년 5월 28일
Thanks! This seems to work perfectly.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by