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?

 채택된 답변

Walter Roberson
Walter Roberson 2017년 11월 30일

0 개 추천

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

Anonymous Anonymous
Anonymous Anonymous 2017년 11월 30일
This worked well thank you.
Anonymous Anonymous
Anonymous Anonymous 2017년 11월 30일
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.
I tried both out and the second one worked better because I didn't get as much repetition in values. Thank you.

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

추가 답변 (0개)

카테고리

도움말 센터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!

Translated by