Nested For Loops Array Indexing
Show older comments
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
More Answers (1)
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.
Categories
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!