# How to generate a joint probability matrix from a data matrix

조회 수: 122(최근 30일)
alpedhuez 2018년 3월 17일
답변: Roger Stafford 2018년 3월 17일
Suppose I have a data matrix
Sample# X Y
1 1 1
2 1 2
3 1 1
Then I want to generate a joint prob matrix
X Y Prob
1 1 0.67
1 2 0.33

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

### 채택된 답변

Michelangelo Ricciulli 2018년 3월 17일
편집: Michelangelo Ricciulli 2018년 3월 17일
Hi, A simple way to get the joint probability matrix for two dimension is using the hist3 function, (read the documentation here ). Let's call your initial matrix nXY
nXY=[1 1 1;
2 1 2;
3 1 1]
You will need only the last two columns to count the occurrence of each combination of X and Y (So, we can use nXY(:,2:3)). Also, you need to define a cell array containing all the possible X values and Y values. In this case, just 1 and 2, so:
Xv=[1 2];
Yv=[1 2];
values={Xv Yv};
count=hist3(nXY(:,2:3),'ctrs',values); %first count the values
p=count/sum(sum(count)); % then divide by the sum on all matrix value to get probability
You will get in the estimated joint probabilities in the matrix p. You'll just need to rewrite them in the form you need.

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

### 추가 답변(1개)

Roger Stafford 2018년 3월 17일
Call the data matrix D. Then the two columns of D(:,2:3) are X and Y.
XY = sortrows(D(:,2:3));
F = find( [true,any(XY(1:end-1,:)~=XY(2:end,:),2),true] );
J = [XY(F(1:end-1),2:3),diff(F)/(F(end)-1)]; % <-- Joint probabilities in column 3
Columns 1 and 2 of J will contain unique X Y pairs.

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

### 범주

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by