6
$\begingroup$

I want to generate a list of numbers with certain conditions. Eg. First I generated 10 random numbers between 1 and 20. M1= RandomReal[{1,20},10] Now I want to create a tabular list which contain numbers M1>9. I have tried M1;While[M1>9];M1; But the condition doesn't work.

$\endgroup$
2
  • 2
    $\begingroup$ one way could be Select[M1, # > 9 &] $\endgroup$
    – Nasser
    Jun 13, 2022 at 11:20
  • 2
    $\begingroup$ Both the title and the first line of your question ask about generating random numbers with constraints, but then your example is about selecting points from a list and creating a "tabular list". It seems the comments and other answers are focusing on the selection of items on a list after the creation of random numbers. Can you please elaborate more on what is precisely what you need? $\endgroup$
    – rhermans
    Jun 13, 2022 at 13:06

2 Answers 2

7
$\begingroup$
SeedRandom[1];
rlist = RandomReal[{1, 20}, 10];

{16.5304, 3.11697, 16.001, 4.56826, 5.58586, 2.24904, 11.3027,
5.39194, 8.52412, 14.309}

Using Select:

Select[rlist,  # > 9 &]

Using Pick:

Pick[rlist, # > 9 & /@ rlist]

Using RegionMember:

First define an implicit region (here you can also use x > 9)

reg = ImplicitRegion[9 < x <= 20, {x}]

Select[rlist, RegionMember[reg, {#}] &]

or use the operator form:

Select[RegionMember[reg, {#}] &][rlist]

Result:

{16.5304, 16.001, 11.3027, 14.309}


Visualization:

NumberLinePlot[{Select[rlist,  # <= 9 &], Select[rlist,  # > 9 &]}, 
 PlotStyle -> {Black, Red}]

enter image description here

$\endgroup$
5
$\begingroup$

One way "to generate a list of numbers with certain conditions" is to create an ImplicitRegion based on your constraints, and then use RandomPoint to sample points in that region.

RandomPoint[
    ImplicitRegion[1<x<20,x]
,10]

enter image description here

$\endgroup$

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.