# Generating a grid such that the elements in each row add up to one

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$$.

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.

• Perfect, thank you! Feb 8, 2019 at 9:02

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.}

• Thanks, but I was trying to construct full grid rather than some random elements of it. Feb 9, 2019 at 7:17