Saving nested for loop data for each successful iteration

5 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 18 Feb 2017
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 Comments
Maitiumc
Maitiumc on 18 Feb 2017
Check is just a counter, I named it check and not count (which is what I have in my actual code) so it wouldn't seem confusing with the fCount I had to count the fail times.
So the way I have in the question is a legit way to do it?
Star Strider
Star Strider on 18 Feb 2017
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.

Sign in to comment.

More Answers (0)

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!