Vectorizing a simple for loop

조회 수: 12 (최근 30일)
Karim Alame
Karim Alame 2011년 12월 3일
Hi everyone, I'm not sure if people asked this before but I tried googling my question before posting.
so i know for this type of loop for example:
for i = 2:n-1
for j = 2:n-1
q(i,j) = a*u(i,j)
end
end
can be simply expressed as: q((2:n-1),(2:n-1)) = a*u((2:n-1),(2:n-1));
what if my expression was as follows: for i = 2:n-1 for j = 2:n-1 q(i,j) = a*u(i+1,j) end end
how could I incorporate the "i+1" expression into vectorizing.
Thank you for your help

채택된 답변

Jan
Jan 2011년 12월 3일
q(2:n-1, 2:n-1) = a*u(3:n, 2:n-1);
  댓글 수: 4
Karim Alame
Karim Alame 2011년 12월 5일
@Jan: Thank you , I ran it again this time and it worked. Interesting thing is I ran it for a 501x501 nodes and the for loop was quicker. The code I posted above is within a larger k loop that updates X=Y.
Thanks again for your help.
Jan
Jan 2011년 12월 5일
The vectorization suffers from the need of large temporary arrays. Allocating memory for "q(2:(nx-1),2:(ny-1))" etc is very expensive, while the multiplication by a scalar is very cheap. Therefore the loop will be more efficient for large inputs.

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

추가 답변 (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