# Randomly splitting of a number in a sum format.

1 view (last 30 days)

Show older comments

Suppose n=5

we can split this number like

5=3+2,4+1..... so on.

But I just want to select a only one sum but randomly and I would like to specify by using varible

like

5=1+3+1

then n_{1}=1, n_{2}=3, n_{3}=1.

How to implement matlab code for any value of n as per above method.

Please help me.

Thanks in advance.

##### 2 Comments

John D'Errico
on 27 Apr 2021

### Accepted Answer

Bruno Luong
on 27 Apr 2021

Edited: Bruno Luong
on 27 Apr 2021

n = 10;

for j=1:10

r = n;

i = 1;

clear s

while r > 0

s(i) = ceil(r*rand);

r = r-s(i);

i = i+1;

end

disp(s)

end

### More Answers (1)

Bruno Luong
on 27 Apr 2021

Edited: Bruno Luong
on 27 Apr 2021

This code will generate "uniform" partition distribution, in the sense that all possible partition has equal probability:

n = 10;

% This part is done once if n is fix

L = 1:n;

p = arrayfun(@(k) nchoosek(n-1,n-k), L);

e = [0, cumsum(p)];

e = e/e(end);

% This part must be repeated when an new random partition is requested

[~,k] = histc(rand,e);

h = diff([0 sort(randperm(n-1,n-k)) n]);

H = mat2cell(L, 1, h)

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!