What is the efficient way to loop though a multidimensional array in matlab?
25 views (last 30 days)
Show older comments
venu on 5 Jan 2023
Answered: Bruno Luong on 5 Jan 2023
I have a fundamental doubt regarding looping across a multidimensional array. while using a for loop to calculate for every element of the matrix, what should be the order of dimensions to loop across. Consider the below code for example:
As can be seen, in the above example, the 3rd dimenison is the outermost loop, followed by 1st, and finally 2nd.
The same code can be written, in which, outermost for loop would be 1st, followed by 2nd, and then 3rd dimensions respectively, or any other order.
Of all the possible ways it can be done, what would be the efficient way to do it?
Does the order of dimensions in the nested for loop affect the speedness of the code?
Bruno Luong on 5 Jan 2023
The inner most loop should be the fist index, the outer most loop last index.
Since MATLAB arranges data with first-dimension vaires first, you'll get more or less a linear memory access and data cache is more efficient.
More Answers (1)
William Rose on 5 Jan 2023
Be sure to allocate all arrays and vectors before doing the looping.
I don't think the order of looping will have a significant effect on speed. I could be wrong. You can check this by trying the different orderings. Put a tic and a toc command before and after the outermost loops, to get the elapsed time, as in the example below. In general, I think it is easy to spend more tme trying to figure out the fastest code than is worth while. It is not worth spending many minutes figuring out a speed advantage of a second or two.
for k=1:20, a(i,j,k)=i+20*j+20*20*k; end
Your code accesses elements k_cv(i+1,j,k), k_cv(i,j+1,k), etc., and Temp_old(i+1,j,k), Temp_old(i,j+1,k), etc. Since i attains a max value of Nx+1, and j goes up to Ny+1, etc., you need to make sure the dimension of k_cv is (Nx+2,Ny+2,Nz+2). Likewise for the dimesions of Temp_old.
Or, if you want k_cv and Temp_old to have dimensions of (Nx,Ny,Nz), then the loops should be i=2:Nx-1,... j=2:Ny-1,... k=2: Nz-1.
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!