4
$\begingroup$

I'd like to generate a grid such that each element is a dimension $d$ vector ($\vec v$) of non negative components that add up to one. I could use the approach in this post and then choose among the resulting grid the points satisfying the constraint that $\vec v.\vec \iota=1,$ but I think it wouldn't be too efficient (as most points won't satisfy the constraint).

Currently, for $d=3$, I make do with nested Do as in

step = .5
Do[
 Print[Chop[{i, j, 1 - i - j}]];
 , {i, 0, 1, step}, {j, 0, 1 - i, step}]

but this requieres me to add additional indexes if I want a larger $d$.

$\endgroup$

2 Answers 2

4
$\begingroup$

You can use IntegerPartitions, which (despite its name) also partitions rationals. Your problem is to partition the number 1 into a set of $d$ nonnegative integer multiples of step:

d = 3;
step = 1/2;
Flatten[Permutations /@ IntegerPartitions[1, {d}, Range[0, 1, step]], 1]
(* {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1/2, 1/2, 0}, {1/2, 0, 1/2}, {0, 1/2, 1/2}} *)

Permutations makes sure that you get all possible partitions in all $d$ dimensions. You may want to use Sort on the result, depending on use case.

$\endgroup$
1
  • $\begingroup$ Perfect, thank you! $\endgroup$
    – Patricio
    Feb 8, 2019 at 9:02
3
$\begingroup$

I think you might be looking for something like this.

myGrid[d_, n_] := (#/Total[#] & /@ RandomReal[1., {n, d}])

This should work for number of rows, n, each having d elements. Let's look at a couple of examples.

SeedRandom[1]; g1 = myGrid[3, 2]

{{0.475687, 0.0648416, 0.459471}, {0.379475, 0.487694, 0.132832}}

Total /@ g1

{1., 1.}

SeedRandom[1]; g2 = myGrid[5, 5]
 {{0.380624, 0.0518834, 0.367649, 0.087452, 0.112392}, 
  {0.0339626, 0.280141, 0.119421, 0.204589, 0.361886}, 
  {0.0812216, 0.287062, 0.162136, 0.0948983, 0.374682}, 
  {0.291637, 0.32702, 0.204302, 0.103509, 0.0735315}, 
  {0.274026, 0.0608128, 0.144656, 0.336122, 0.184383}}
Total /@ g2

{1., 1., 1., 1., 1.}

$\endgroup$
1
  • $\begingroup$ Thanks, but I was trying to construct full grid rather than some random elements of it. $\endgroup$
    – Patricio
    Feb 9, 2019 at 7:17

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.