Randomly splitting of a number in a sum format.

조회 수: 10 (최근 30일)
rohini more
rohini more 2021년 4월 27일
댓글: rohini more 2021년 4월 27일
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
John D'Errico
John D'Errico 2021년 4월 27일
편집: John D'Errico 2021년 4월 27일
PLEASE STOP ASKING THE SAME QUESTION!
You have asked 6 questions so far on ANSWERS. 5 of them have been essentially duplicates. The rest of them had answers already, but I just closed the latest one, and will now close further duplicate questions by you. You have already gotten multiple answers to your question.
John D'Errico
John D'Errico 2021년 4월 27일
편집: John D'Errico 2021년 4월 27일
No. There have been multiple questions about random partitions of a set. Learn how to find the set of all partitions, then choose one randomly. You cannot create variable names on the fly, and to the extent that you can do so, you SHOULD not. Instead, learn to use vectors.

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

채택된 답변

Bruno Luong
Bruno Luong 2021년 4월 27일
편집: Bruno Luong 2021년 4월 27일
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
4 2 4 8 1 1 7 3 4 2 2 1 1 8 1 1 7 1 1 1 7 1 1 1 10 8 2 1 9
  댓글 수: 12
Bruno Luong
Bruno Luong 2021년 4월 27일
Ops I have a typo in my code, can you try again.
rohini more
rohini more 2021년 4월 27일
Now its working . Thank you very much.

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2021년 4월 27일
편집: Bruno Luong 2021년 4월 27일
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)
H = 1×2 cell array
{[1 2 3 4 5]} {[6 7 8 9 10]}
  댓글 수: 1
rohini more
rohini more 2021년 4월 27일
Thanks for giving your valuable time for solving my question. It really means a lot.
Thank you very much.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by