Performing Chi Square Test
조회 수: 180 (최근 30일)
이전 댓글 표시
Hey everyone,
i want to perform a Chi-Square Test on the given data table:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1136005/image.png)
The solution for the calculation looks like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1136010/image.png)
Now as you see the result should be 507.93 (I am totally aware that this is not very meaningful in terms of the test but anyway this is what should be returned.)
I've tried with crosstab function in Matlab but could not get it to do what I wanted.
Hope someone can help a Matlab Newbie ;)
Best regards.
댓글 수: 0
답변 (2개)
Torsten
2022년 9월 25일
Source:
% First way
n1 = 50; N1 = 300;
n2 = 1000; N2 = 1200;
x1 = [repmat('a',N1,1); repmat('b',N2,1)];
x2 = [repmat(1,n1,1); repmat(2,N1-n1,1); repmat(1,n2,1); repmat(2,N2-n2,1)];
[tbl,chi2stat,pval] = crosstab(x1,x2)
% Second way
n1 = 50; N1 = 300;
n2 = 1000; N2 = 1200;
% Pooled estimate of proportion
p0 = (n1+n2) / (N1+N2);
% Expected counts under H0 (null hypothesis)
n10 = N1 * p0;
n20 = N2 * p0;
% Chi-square test, by hand
observed = [n1 N1-n1 n2 N2-n2];
expected = [n10 N1-n10 n20 N2-n20];
chi2stat = sum((observed-expected).^2 ./ expected)
p = 1 - chi2cdf(chi2stat,1)
댓글 수: 0
the cyclist
2022년 9월 25일
The crosstab function calculates the table from raw data. It does not expect the table itself as input.
After an admittedly brief search, I did not find a MATLAB function that calculates the chi-square stat from the table. Here is a function that "reverse engineers" the data from the table, and then calculates the stat:
M = [250 200 450;
50 1000 1050;
300 1200 1500];
[x,y] = inversecrosstab(M);
[tbl,chi2] = crosstab(x,y)
function [xVec,yVec] = inversecrosstab(tab)
% INVERSECROSSTAB takes table of values (as would be output by CROSSTAB) and creates
% X and Y vectors that would have led to that cross-tabulation table
[nxdim nydim] = size(tab);
[xVec,yVec] = deal([]);
val = 0;
for ix = 1:nxdim
val = val + 1;
for iy = 1:nydim
xVec = [xVec;repmat(val,[tab(ix,iy),1])];
yVec = [yVec;repmat(iy, [tab(ix,iy),1])];
end
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Hypothesis Tests에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!