Vectorization of nested loops using mtimesx
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Matt J
am 12 Dez. 2013
Bearbeitet: Matt J
am 12 Dez. 2013
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.
Antworten (1)
Andrei Bobrov
am 17 Dez. 2013
for your case:
ufn = bsxfun(@times,u(1:3,:,:,:),fct(end,:)');
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!