While trying to solve a problem I came across the following question (it closely relates to the issue I'm having):
I want to know if this can be done using Randi? One of the answers to that particular question demonstrates a method using Randi; however, it involves a for loop. Is there a way of achieving the same outcome without the for loop?

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 30 Nov. 2017

0 Stimmen

Assuming two vectors of equal sizes, A (representing minimum values) and B (representing maximum values), and assuming that you want to generate one random value for each entry, then
BAspan = B - A + 1;
span_required = fold( @lcm, BAspan(:).' );
R = randi([0 span_required-1], size(A));
C = A + mod(R, BAspan);

4 Kommentare

Anonymous Anonymous
Anonymous Anonymous am 30 Nov. 2017
This worked well thank you.
Anonymous Anonymous
Anonymous Anonymous am 30 Nov. 2017
I have an additional question. What would I do if I wanted to add a constraint that dictates that the consecutive integers cannot be less than the previous integer. That is, if C is a [1x200] matrix, how can I ensure that the value of C(:,2) is greater than C(:,1) and the value of C(:,3) is greater than the value of C(:,2) etc etc.
If all of the bounds are the same, then sort() the values afterwards (though that in itself leaves open the possibility that values could be equal.)
If the bounds are all the same, consider changing strategy:
BAspan = B(1) - A(1) + 1;
if BAspan < 200; error('Not enough room in those bounds to generate 200 integers'); end
C = sort(A(1) + randperm(BAspan, 200) - 1);
These values are guaranteed to be different.
Anonymous Anonymous
Anonymous Anonymous am 4 Dez. 2017
I tried both out and the second one worked better because I didn't get as much repetition in values. Thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by