Nested For Loops Array Indexing

Hi,
I'm trying to optimize a piece of code by allocating a matrix to zeros initially, rather than resetting the value each time in the for loop. The aim of this is to make the for loop run faster and sum the T and D variables.
I have simplified my code to:
endtime=200;
for time=1:endtime
for i=1:6
for j=1:6
for k=1:6
for p=1:6
D(i*j*k,time)=D(i*j*k,time)+otherfunctions(i,p,k);
end
T(i+1,time)=T(i+1,time)+D(i*j*k,time)*qd(k,time)*qd(j,time);
end
end
end
end
I would like to reset the value of D every time the k loop is entered. I know this can be achieved through just setting D=0 after "T(i+1,time)=...." however this would be done 6^3 * endtime times. Surely it would be more efficient to allocate D as a matrix of zeros initially and then cycle through the D matrix. I've tried to do this through D(i*j*k,time) but obviously I get the same array index for different values of i, j and k because their product is the same but their sequence is different. Can anybody help me?

 Accepted Answer

idx = sub2ind( [6 6 6], i, j, k);
D( idx, time ) = ...;
will allow you to make best use of indexing into D without over-writing values or leaving massive gaps in the matrix.

1 Comment

Exactly what I was after - thank you for your help

Sign in to comment.

More Answers (1)

Thorsten
Thorsten on 12 Dec 2014
Edited: Thorsten on 12 Dec 2014
If you don't need the various D values for the different times, you can use
for time ...
for i ...
for j ...
D = 0;
for k ...
D = D + otherfunctions(i,p,k);
end
T(i+1,time)= ... + D + ...
end
end
end
If you have to save values of D for different times, use D(time) instead of D.

3 Comments

Thanks, I don't need to save the D values but in your example I'm now setting D time*i*j times, whereas I'd prefer to preallocate D so it's something like
D=zeros(maxi*maxj*maxk,time)
I'm hoping this will improve the efficiency so I'm not doing D=0 so many times in my for loop.
Thorsten
Thorsten on 12 Dec 2014
Edited: Thorsten on 12 Dec 2014
Setting D=0 many times is no problem. What is a problem if you have an array that grows within your loop, like T. For T it's faster if you preallocate a variable of the right size before the loops.
Sorry, my example is incomplete as it's only a snippet of my code I do already preallocate for T.

Sign in to comment.

Categories

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

Asked:

on 12 Dec 2014

Commented:

on 12 Dec 2014

Community Treasure Hunt

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

Start Hunting!