Vectorization of nested loops using mtimesx

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 Comments

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.
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.

Sign in to comment.

Answers (1)

for your case:
ufn = bsxfun(@times,u(1:3,:,:,:),fct(end,:)');

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 12 Dec 2013

Answered:

on 17 Dec 2013

Community Treasure Hunt

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

Start Hunting!