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
Star Strider
Star Strider 2018년 11월 28일
‘I believe I would need to use the while loop...
I agree.
Jos (10584)
Jos (10584) 2018년 11월 28일
Depending on what "I need it to stop" exactly means, you may also benefit from using cumsum

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
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
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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by