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.

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2018년 9월 7일
편집: Stephen23 2018년 9월 7일
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

Thanks a lot, Stephen, beautiful code!
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개)

Bruno Luong
Bruno Luong 2018년 9월 7일
편집: Bruno Luong 2018년 9월 7일
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에 대해 자세히 알아보기

질문:

2018년 9월 7일

댓글:

2018년 9월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by