Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m writing a Matlab program for school and I have nested for-loops that create

ID: 3626800 • Letter: I

Question

I'm writing a Matlab program for school and I have nested for-loops that create a 4-dimensional array (of the distances between every two points with coordinates (x,y) and (x',y')) as below:

d_x and d_y are just 20x20 matrices and Lx=Ly for trial purposes. It's very slow to use so many nested loops and obviously not a very elegant way of doing it. I tried to vectorize the nested loops and succeeded in getting rid of the two inner loops as:

which basically replaces the 4 for-loops above. I've now been trying for 2 days but I couldn't find a way to vectorize the two remaining loops as well. I wanted to ask:

Any advice will be greatly appreciated.

Explanation / Answer

Yes you can always and always eliminate nested loops. This is the trick. define a counter variable. Counter=1 let the outer loop go from 1 to Ly*Lx add a condition statement to reset the counter Counter=1 for l=1:Ly*Lx dy2(l,k,:,:)=repmat(d_y(l,:),Ly,1); dx2(l,k,:,:)=repmat(d_x(Counter,:)',1,Lx); if (Counter>= Lx ) Counter=1 else Counter=Counter+1 end end