Vectorizing a simple for loop

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 日

0 投票

q(2:n-1, 2:n-1) = a*u(3:n, 2:n-1);

4 件のコメント

Karim Alame
Karim Alame 2011 年 12 月 4 日
that's what I thought so basically I have this :
for i = 2:nx-1
for j = 2:ny-1
Y(i,j) = q(i,j) - a*X(i+1,j) -b*X(i,j+1) -a*X(i-1,j) -b*X(i,j-1);
end
end
where X is a (nx)x(ny) matrix & a and b are constants.
following what you wrote :
Y(2:(nx-1),2:(ny-1)) = q(2:(nx-1),2:(ny-1)) - a*X(3:nx,2:(ny-1)) - b*X(2:nx-1,3:ny) - a*X(1:(nx-2),2:(ny-1)) - b*X(2:(nx-1),1:(ny-2));
I get an error for matrix dimension mismatch, which makes sense for a vectorized form. I know for multiplication or division I can add(.), any suggestions ?
Thank you in advance I appreciate it.
Jan
Jan 2011 年 12 月 4 日
@Karim: I do not get an error when I run the code you've posted. Are you sure, that the error message concerns this line?
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 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2011 年 12 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by