MATLAB: How to create a matrix where every combination of numbers between 0 and 1 (step x) is used and every row sums to one

combinationpermutation

Hello everybody,
I'm looking for a way to create a matrix where every row sums to one and every combination of numbers between zero and one is used given a specified step parameter.
Example: 3 Columns; Step 0.5:
Row 1:[0 0.5 0.5] Row 2:[0.5 0 0.5] Row 3:[0.5 0.5 0]
I'm using the following code (for 6 columns) which is too slow given a small step parameter:
i=1;
for a = 0:step:0.5
for b = 0:step:0.5
for c = 0:step:0.5
for d = 0:step:0.5
for e = 0:step:0.5
for f = 0:step:0.5
weights(i,:)=[a b c d e f];
i = i+1;
end
end
end
end
end
end
clear a b c d e f i
ind = sum(weights,2) == 1;
weights = weights(ind,:);
Thank you for your help!

Best Answer

for step stp = .5
stp = .5;
ii = cell(1,6);
[ii{:}] = ndgrid(0:stp:1);
out = cell2mat(cellfun(@(x)x(:),ii(:,end:-1:1),'un',0));
out = out(sum(out,2) == 1,:);
OR
x = 0:stp:1;
out = x(fliplr(fullfact(numel(x)*ones(1,6))));
out = out(sum(out,2) == 1,:);