How to add existing values of an array with each other until a certain value is reached
17 次查看(过去 30 天)
显示 更早的评论
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...
2 个评论
Jos (10584)
2018-11-28
Depending on what "I need it to stop" exactly means, you may also benefit from using cumsum
采纳的回答
Adam Danz
2018-11-28
编辑:Adam Danz
2018-11-28
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
3 个评论
Adam Danz
2018-11-28
编辑:Adam Danz
2018-11-28
The line find(foobar, 3) just finds the first 3 true indices of the logical vector foobar.
If you want to start the cumulative sum at the 3rd element of randSamp,
randSamp = rand(1,5000);
startAt = 3; %start at 3rd element.
csum = cumsum(randSamp(startAt:end)); %cumulative sum from sample 3, onward.
crossIdx = find(csum >=1, 1); %find index of the first number > 1.
randSamp(crossIdx + startAt : end) = []; %don't forget to offset by 'startAt'.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!