Vectorization of nested loops using mtimesx

2 次查看(过去 30 天)
Hello everybody,
I need some help with the following questions:
1) I'm trying to improve the performance of some code. After running the profiler, I see that most of the run time (~75%) is spent on the following loops:
for i=1:Ny*Nz,
for j=1:Ny,
for k=1:Nz,
ufn(1,:,j,k)=fct(i,1).*u(1,:,j,k);
ufn(2,:,j,k)=fct(i,2).*u(2,:,j,k);
ufn(3,:,j,k)=fct(i,3).*u(3,:,j,k);
end;
end;
end;
where the size of the arrays corresponds to
fct=zeros(Ny*Nz,3)
ufn=zeros(3,Nx,Ny,Nz)
I'm trying with mimesx but I'm having problems to vectorize these multiplications (I tried different ways to reshape fct without success). In particular, I can't figure the proper way to get the desired size of ufnt.
Could someone be so kind to indicate how to do this?
2) Assuming the above is done avoiding loops, will this represent a dramatical increase in memory request? I need to use arrays of about Nx=4096, Ny=Nz=512 and I wonder if for that size, the loop solution could be actually more efficient (demand less memory without a dramatic increase of time).
Thank you,
Hugo
  2 个评论
Matt J
Matt J 2013-12-12
编辑:Matt J 2013-12-12
You seem to have some typos in your code, making it hard to understand what you are trying to do.
First, you are looping over i with no meaningful effect on the left hand sides of
ufn(1,:,j,k)=fct(i,1).*u(1,:,j,k);
ufn(2,:,j,k)=fct(i,2).*u(2,:,j,k);
ufn(3,:,j,k)=fct(i,3).*u(3,:,j,k);
since the index i never appears there.
Secondly all of your operations are scalar multiplications with no summations. Since matrix multiplications involve a mixture of scalar multiplications and additions, it's hard to see why you think mtimesx will be applicable here.
hugoles
hugoles 2013-12-17
You're absolutely right, there are big typos in those lines. The problem is actually much simpler than a matrix multiplication.
Thank you for having pointed that out.

请先登录,再进行评论。

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2013-12-17
for your case:
ufn = bsxfun(@times,u(1:3,:,:,:),fct(end,:)');

类别

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