8
$\begingroup$

I know that you can generate an $m\times n$ matrix of random numbers by RandomReal[range, {m, n}], where e.g. range = {0, 1}.

Is there a way to generate an $m\times n$ matrix of random numbers and have each column entry be drawn from a different range?

My question is, if there is something analogous to RandomReal[{range1,range2,...,rangen},{m,n}] (which obviously does not evaluate because it is not supported).

My current solution to this problem is using Map; i.e.

 Transpose[
   Map[
     RandomReal[#,m]&,
     {range1,range2,...,rangen}
   ]
  ]

where m is the desired number of $n$-tuples of random numbers from $n$ different ranges that I need.

Is there a better alternative to this?

$\endgroup$

1 Answer 1

10
$\begingroup$

The simplest way is to use UniformDistribution[] in RandomVariate[]:

BlockRandom[SeedRandom[42]; (* for reproducibility *)
            RandomVariate[UniformDistribution[{{3, 4}, {5, 7}}], 4]]
   {{3.42591, 6.11193}, {3.39102, 5.57834}, {3.34707, 5.5937}, {3.45374, 5.41282}}

Alternatively, you can use RescalingTransform[] on the results of RandomReal[]:

scaledRandomReal[ranges_?MatrixQ, n_Integer] := With[{m = Length[ranges]}, 
      RescalingTransform[ConstantArray[{0, 1}, m], ranges][RandomReal[1, {n, m}]]]

BlockRandom[SeedRandom[42]; scaledRandomReal[{{3, 4}, {5, 7}}, 4]]
   {{3.42591, 5.78205}, {3.34707, 5.90748}, {3.55596, 5.57834}, {3.29685, 5.41282}}
$\endgroup$
3
  • $\begingroup$ Are there advantages to the first form (RandomVariate[UniformDistribution[...) over Transpose[RandomReal[#,4]&/@{{3,4},{5,7}}]? $\endgroup$
    – orome
    Commented Nov 1, 2017 at 12:55
  • $\begingroup$ Yes, that works too. I just didn't want to use slots. $\endgroup$ Commented Nov 1, 2017 at 13:14
  • $\begingroup$ I think I'll use UniformDistribution because it's easier to wrap my head around it; RescalingTransform is really interesting and it's kind of embarrassing not knowing anything about it even though it's a 10 years old feature; +1 for the people at Wolfram $\endgroup$
    – user42582
    Commented Nov 2, 2017 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.