Performing Chi Square Test

10 views (last 30 days)
Alexander Tollinger
Alexander Tollinger on 25 Sep 2022
Answered: Torsten on 25 Sep 2022
Hey everyone,
i want to perform a Chi-Square Test on the given data table:
The solution for the calculation looks like this:
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.

Answers (2)

the cyclist
the cyclist on 25 Sep 2022
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)
tbl = 3×3
250 200 450 50 1000 1050 300 1200 1500
chi2 = 507.9365
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

Torsten
Torsten on 25 Sep 2022
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)
tbl = 2×2
50 250 1000 200
chi2stat = 507.9365
pval = 1.7831e-112
% 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)
chi2stat = 507.9365
p = 1 - chi2cdf(chi2stat,1)
p = 0

Community Treasure Hunt

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

Start Hunting!