MATLAB: How to add existing values of an array with each other until a certain value is reached

randwhile loop

So I am tasked with using a rand function to generate many random numbers between 0-1.
After doing so and storing them in an array, I have to add each element until the sum exceeds 1, then stop there.
Ex: Say x = rand(1, 6) generates (0.12, 0.44, 0.33, 0.32, 0.55, 0.19). I would need sum up just 0.12, 0.44, 0.33, and 0.32.
sum(x) would not work as that just sums of all the generated numbers. I need it to stop immediately after it exceeds 1.
I believe I would need to use the while loop…

Best Answer

If you are drawing random numbers between [0, 1] until the sum of your draws reaches 1.0, you'll likely only draw a few numbers (1 to 5, let's say). Its highly unlikely that you'll need much more than that but sometimes you will. So we will draw 5000 just to be safe.
This solution draws 5000 random numbers between [0, 1], calucalutes the cumulative sum, and then detects when the cumulative sum crosses the 1.0 value, eliminating all samples that follow.
randSamp is your list of random variables whose cumulative sum just passes 1.0.
randSamp = rand(1,5000);
crossIdx = find(cumsum(randSamp) >=1, 1);
randSamp(crossIdx+1 : end) = [];
If for some reason you need a while loop,
randSamp = [];
while sum(randSamp) < 1
randSamp(end+1) = rand();
end