% % Simulerer data fra ulike regresjonsmodeller, estimerer % residualer i en enkel lineær regresjonsmodell og % lager residualplott % n = 100; figure(1); figure(2); pause; % betrakter først modellen Y = 0.5 + 1.5x + epsilon, epsilon ~ n(.;0,1) x = unifrnd(-1,1,n,1); y = 0.5 + 1.5 * x + normrnd(0,1,n,1); figure(1); plot(x,y,'.'); title('kryssplott'); betahat = sum((x-mean(x)) .* y) / sum((x-mean(x)).^2); alphahat = mean(y) - betahat * mean(x); residualhat = y - alphahat - betahat * x; hold on; plot([min(x) max(x)],alphahat + betahat * [min(x) max(x)],'r-'); hold off; figure(2); plot(x,residualhat,'.'); title('residualplott'); hold on; plot([min(x) max(x)],[0 0],'r-'); hold off; pause; % betrakter så en modell med ikke-lineær forventning x = unifrnd(-1,1,n,1); y = 0.5 + 1.5 * x + 4 * x.^2 + normrnd(0,1,n,1); figure(1); plot(x,y,'.'); title('kryssplott'); betahat = sum((x-mean(x)) .* y) / sum((x-mean(x)).^2); alphahat = mean(y) - betahat * mean(x); residualhat = y - alphahat - betahat * x; hold on; plot([min(x) max(x)],alphahat + betahat * [min(x) max(x)],'r-'); hold off; figure(2); plot(x,residualhat,'.'); title('residualplott'); hold on; plot([min(x) max(x)],[0 0],'r-'); hold off; pause; % en annen modell med ikke-lineær forventning x = unifrnd(-1,1,n,1); y = exp(2.5 * x) + normrnd(0,1,n,1); figure(1); plot(x,y,'.'); title('kryssplott'); betahat = sum((x-mean(x)) .* y) / sum((x-mean(x)).^2); alphahat = mean(y) - betahat * mean(x); residualhat = y - alphahat - betahat * x; hold on; plot([min(x) max(x)],alphahat + betahat * [min(x) max(x)],'r-'); hold off; figure(2); plot(x,residualhat,'.'); title('residualplott'); hold on; plot([min(x) max(x)],[0 0],'r-'); hold off; pause; % så en modell med ikke-konstant varians x = unifrnd(-1,1,n,1); y = 0.5 + 1.5 * x + 0.5 * (x.^2 + 0.1) .* normrnd(0,1,n,1); figure(1); plot(x,y,'.'); title('kryssplott'); betahat = sum((x-mean(x)) .* y) / sum((x-mean(x)).^2); alphahat = mean(y) - betahat * mean(x); residualhat = y - alphahat - betahat * x; hold on; plot([min(x) max(x)],alphahat + betahat * [min(x) max(x)],'r-'); hold off; figure(2); plot(x,residualhat,'.'); title('residualplott'); hold on; plot([min(x) max(x)],[0 0],'r-'); hold off; pause; % så en modell med skjev fordeling x = unifrnd(-1,1,n,1); y = 0.5 + 1.5 * x + 0.5 * (exprnd(1,n,1) - 1); figure(1); plot(x,y,'.'); title('kryssplott'); betahat = sum((x-mean(x)) .* y) / sum((x-mean(x)).^2); alphahat = mean(y) - betahat * mean(x); residualhat = y - alphahat - betahat * x; hold on; plot([min(x) max(x)],alphahat + betahat * [min(x) max(x)],'r-'); hold off; figure(2); plot(x,residualhat,'.'); title('residualplott'); hold on; plot([min(x) max(x)],[0 0],'r-'); hold off; pause