Saving nested for loop data for each successful iteration
조회 수: 5 (최근 30일)
이전 댓글 표시
I'm trying to store the data for each time a certain criteria is met, the criteria is calculated using the number of hours (it is a failure rate, so failure % = fail count/t * 100, where t is the hours). The loop is run 300 times using different system configurations. A simplified verision:
check = 0; %check is just a counter to count the number of iterations
%x1-3 are the variable system parameters
for x1 = 1:3
for x2 = 1:10
for x3 = 1:10
check = check+1
for t=1:length(time)
...
do something
%calculate fail
fail = fCount/t
if fail<desiredFail
store(t,:) = [x1, x2, x3, fail]
end
end
end
end
end
So clearly the issue here is that using t as the index will only store the final iteration results (x1=3, x2=10, x3=10) and the saved values is overwritten each time the loop goes round. I have tried to add the array to another array using cat, but this failed for similar reasons.
As I was about to post this, I thought of a simple solution but it seems way too easy to be correct given the amount of similar questions on this problem. I have added the check variable, which is going to be equal to the number of iterations. If I used this variable ie:
if true
store(check,:) = [x1,x2,x3,fail]
end
Will this work? I have run it with this code and it gives me the 300 values, but as my code is full of bugs at the minute I'm not totally convinced by this method, seems too simplistic compared to the other answers I've seen suggested (which I didn't fully understand how I could apply them hence I asked my own question).
Thanks in advance.
댓글 수: 0
채택된 답변
Star Strider
2017년 2월 18일
I’m not certain what ‘check’ is. I would just add a counter:
count = 0; % Initilise Counter
... CODE ...
if fail<desiredFail
count = count + 1; % Increment Counter
store(count,:) = [x1, x2, x3, t, fail]
end
... CODE ...
댓글 수: 2
Star Strider
2017년 2월 18일
If you did with ‘check’ the same as I did with ‘count’, then yes!
Create a separate counter for your ‘store’ array, use ‘store’ to keep track of the loop variables and other relevant results at the time the condition was met, and you have all the information you need when your code successfully completes.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 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!