How to make 3 random numbers that sum to 1

조회 수: 74 (최근 30일)
Samual
Samual 2017년 9월 29일
댓글: CLOUDY LU 2020년 3월 8일
I'm trying to make two matrices for 6 random numbers, and the three different numbers of each need to sum up to 1. ex)P1+P2+P3=1 . How can I make this?? thanks. this is some part of my script file.
P1=rand(1,1)
P2=rand(1,1)
P3=rand(1,1)
Q1=rand(1,1)
Q2=rand(1,1)
Q3=rand(1,1)
if (P1+P2+P3==1) && (Q1+Q2+Q3==1)
%setting P, Q matrix
P=[P1 P2 P3];
Q=[Q1; Q2; Q3];

답변 (2개)

Image Analyst
Image Analyst 2017년 9월 29일
Did you try this:
r = rand(1, 3); % Start with 3 random numbers that don't sum to 1.
r = r / sum(r) % Normalize so the sum is 1.
theSum = sum(r) % Check to make sure. Should be 1
  댓글 수: 3
krishna vasishta
krishna vasishta 2018년 4월 12일
It works!! Many thanks!!!
CLOUDY LU
CLOUDY LU 2020년 3월 8일
Wonderful idea! Thanks!

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


Roger Stafford
Roger Stafford 2018년 3월 5일
편집: Stephen23 2018년 3월 5일
If you want your results statistically uniform area-wise, you can use the 'randfixedsum' function in the File Exchange at:

Community Treasure Hunt

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

Start Hunting!

Translated by