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?
채택된 답변
추가 답변 (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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!