% MS-A0503 spring 2022 % Example of a discrete joint distribution of two variables. % (MATLAB/Octave code) % % X = #persons in household % Y = #rooms in household % P(X=x, Y=y) = proportion of such households x = 1:6; y = (1:6)'; pxy = [ 0.126 0.013 0.002 0.001 0.000 0.000 0.196 0.086 0.012 0.005 0.001 0.000 0.073 0.097 0.034 0.019 0.005 0.001 0.038 0.079 0.031 0.030 0.010 0.003 0.015 0.041 0.017 0.021 0.009 0.002 0.004 0.012 0.006 0.007 0.003 0.001 ]; % Marginal distribution of X, by taking column sums px = sum(pxy, 1) % Marginal distribution of Y, by taking row sums py = sum(pxy, 2) % Expectations, using the definition of E ex = sum(x .* px) ey = sum(y .* py) % Variances and standard deviations vx = sum((x-ex).^2 .* px); sdx = sqrt(vx) vy = sum((y-ey).^2 .* py); sdy = sqrt(vy) % Covariance and correlation covxy = sum(sum((x-ex).*(y-ey).*pxy)) corxy = covxy / sdx / sdy % Color picture of the bivariate distribution. % Dark = large value. imagesc(pxy); colormap(1-gray); colorbar; set(gca,'ydir','normal'); title('Finnish households') xlabel('X = #persons') ylabel('Y = #rooms')