|
"Farhan Rahman" <farban@gmail.com> wrote in message <gvei09$3hm$1@fred.mathworks.com>...
> Hi everyone,
>
> I'm trying to vectorize a series of nested for loops within a larger script in order to optimize the performance of it. This seems like it should be fairly simple, but after a lot of messing about with it I haven't managed to make much headway.
>
> Here's a section of my code that I'm having trouble with:
>
> for i=2:nhx-1
> for j=2:nhy-1
> Unew(i,j)= U(i,j)-dt*(P(i+1,j)-P(i-1,j))/(2*hx)...
> +nu*dt*(1/(hx*hx)*(U(i+1,j)-2.*U(i,j)+U(i-1,j))...
> +1/(hy*hy)*(U(i,j+1)-2.*U(i,j)+U(i,j-1)))...
> -dt*U(i,j)/(hx)*(U(i,j)-U(i-1,j))...
> -dt*V(i,j)/(2*hy)*(U(i,j+1)-U(i,j-1));
> end
> end
>
> nhx and nhy are predefined vectors, and U, Unew and P are preallocated matrices of zeros. dt, hx and hy are all static single values.
>
> Hopefully someone can help,
>
> Cheers :)
If you have recent MATLAB that support bsxfun (from 2007A IIRC), You can use bsxops to remove the loop!
http://www.mathworks.com/matlabcentral/fileexchange/23821
bsxops(1);
i = 2:nhx-1;
j = 2:nhy-1;
Unew(i,j)= U(i,j)-dt*(P(i+1,j)-P(i-1,j))/(2*hx)...
+nu*dt*(1/(hx*hx)*(U(i+1,j)-2.*U(i,j)+U(i-1,j))...
+1/(hy*hy)*(U(i,j+1)-2.*U(i,j)+U(i,j-1)))...
-dt*U(i,j)./(hx).*(U(i,j)-U(i-1,j))...
-dt*V(i,j)./(2*hy).*(U(i,j+1)-U(i,j-1));
bsxops(0);
% Bruno
|