Using Randi with min and max matrices

2 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 30 Nov 2017
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 Comments
Walter Roberson
Walter Roberson on 30 Nov 2017
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 on 4 Dec 2017
I tried both out and the second one worked better because I didn't get as much repetition in values. Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!