How to add existing values of an array with each other until a certain value is reached
20 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Daniel Kwak
il 28 Nov 2018
Commentato: Daniel Kwak
il 28 Nov 2018
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 Commenti
Jos (10584)
il 28 Nov 2018
Depending on what "I need it to stop" exactly means, you may also benefit from using cumsum
Risposta accettata
Adam Danz
il 28 Nov 2018
Modificato: Adam Danz
il 28 Nov 2018
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 Commenti
Adam Danz
il 28 Nov 2018
Modificato: Adam Danz
il 28 Nov 2018
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'.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!