How to create matrix with fixed sum in rows and fixed increment in elements

I would like to create a 231*3 matrix whose elements are all multiples of 0.05 and the sum of each row be equal to 1.
E.g.
0 0 1
0 0.05 0.95
0.05 0 0.95
0 0.1 0.90
0.1 0 0.90
0.05 0.05 0.90
......

1 个评论

Sorry about the ambiguity, actually I want this matrix to contain all the possible combinations of multiples of 0.05, without duplicated rows in the matrix.

请先登录,再进行评论。

 采纳的回答

Straightforward exhaustive search which does not generate any superfluous rows:
V = 0:5:100;
Z = nan(0,3);
for n1 = V
for n2 = V
for n3 = V
if (n1+n2+n3)==100
Z(end+1,:) = [n1,n2,n3];
end
end
end
end
Z = Z/100;
This gives all 231 unique rows:
>> Z
Z =
0.00000 0.00000 1.00000
0.00000 0.05000 0.95000
0.00000 0.10000 0.90000
0.00000 0.15000 0.85000
0.00000 0.20000 0.80000
0.00000 0.25000 0.75000
0.00000 0.30000 0.70000
0.00000 0.35000 0.65000
0.00000 0.40000 0.60000
0.00000 0.45000 0.55000
0.00000 0.50000 0.50000
0.00000 0.55000 0.45000
0.00000 0.60000 0.40000
0.00000 0.65000 0.35000
0.00000 0.70000 0.30000
... lots of rows here
0.85000 0.05000 0.10000
0.85000 0.10000 0.05000
0.85000 0.15000 0.00000
0.90000 0.00000 0.10000
0.90000 0.05000 0.05000
0.90000 0.10000 0.00000
0.95000 0.00000 0.05000
0.95000 0.05000 0.00000
1.00000 0.00000 0.00000
>> size(Z)
ans =
231 3
>> size(unique(Z,'rows'))
ans =
231 3

4 个评论

As is often the case, it is a trade-off between memory and speed. My solution is slightly faster, but yours will consume less memory (especially for cases with smaller step sizes).
"My solution is slightly faster, but yours will consume less memory (especially for cases with smaller step sizes)."
The speed of my answer could be improved by preallocation and using a counter as the index:
Z = nan(231,3);
K = 0;
...
K = K+1;
Z(K,:) = [...];
...
I guess there is also some formula for getting "231", but it escapes me at this moment...
The formula is 231=nchoosek(20+3-1,3-1), you can see my code to see why.

请先登录,再进行评论。

更多回答(1 个)

s = 0.05;
n = round(1/s);
m = 3;
r = nchoosek(1:n+m-1,m-1);
z = zeros(size(r,1),1);
r = (diff([z, r, n+m+z],1,2)-1)/n

4 个评论

I don't know if it is relevant, but this method is not guaranteed to give unique rows.
I miss understood whereas OP wants random or all combinations. Now I fix it since the number of combinations is just 231.
Thank you guys, this now works perfectly well.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by