필터 지우기
필터 지우기

Generating random numbers within a range determined by elements in another array

조회 수: 2 (최근 30일)
Hello,
I was wondering if there is an efficient way to generate a random integer within a range depending on an element in another array. Perhaps a small example will explain better:
1 must generate a random number in [3 7];
2 must generate a random number in [1 3];
3 must generate a random number in [44 66]
So for the vector [3 1 2] I would want to get another vector [59 4 2], for example.
I was thinking of using arrayfun to do this but I don't know if there is a more efficient way?
Any help/advice would be greatly appreciated.
Thanks

채택된 답변

Iain
Iain 2013년 5월 21일
편집: Andrei Bobrov 2013년 5월 22일
Array = [3 7; 1 3; 44 66];
Choose your row, "i"
NewRandom = roundingfunctionofchoice(rand(size(i)).*(Array(i,2)-Array(i,1)) + Array(i,1));
If you set i = [3 1 2], you'll get what you want.
  댓글 수: 1
Ray
Ray 2013년 5월 22일
Thanks! I tested this on a huge example and it was very efficient, better than my use of for-loops/while-loops.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2013년 5월 21일
Did you look at the help for rand() and notice the first example? Here it is:
Example 1
Generate values from the uniform distribution on the interval [a, b]:
r = a + (b-a).*rand(100,1);
Basically it all comes down to that. Do that 3 times with different a and b depending on what the 3 numbers are. Is this homework?
  댓글 수: 1
Ray
Ray 2013년 5월 22일
I am familiar with the rand function. I was looking more for a compact/efficient approach to achieving the random number generation based on differing ranges, unique to each element in the first array (see accepted answer above).

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

Community Treasure Hunt

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

Start Hunting!

Translated by