필터 지우기
필터 지우기

How do I make a vector of fitted values and a vector of residual values from a linear model of y on x

조회 수: 14 (최근 30일)
Hi I'm trying to make a function that
  1. Gives me a vector of fitted values based off of a linear model of y on x
  2. Gives me a vector of residual values from the linear model of y on x.
I have the basic function layout (I'm also calculating other things) and a code to call the function but I dont really know how to find the vectors for the fitted values and residual values. Below is the code that I already have. Thanks.
function [intercept, slope, resVar, fit, res] = fitLinearModel(x,y)
%intercept
P = polyfit(x,y,1);
intercept=P(2);
%slope
slope=P(1);
%resVar
A = [ones(numel(x),1),x.'];
b = y.';
c = A\b;
format long
resVar=var(y-(c(1)+c(2)*x))*(numel(x)-1)/(numel(x)-2);
%fit - this is a vector of the fitted values from the linear model of y on x
fit=;
%res - this is a vector of the residual values from the linear model of y
%on x
res=;
end
Code to call function:
x = normrnd(10, 1, 1, 100);
y = 1 + 2 .* x + normrnd(0, 1, 1, 100);
[intercept, slope, resVar, fit, res] = fitLinearModel(x,y);
  댓글 수: 1
dpb
dpb 2022년 9월 5일
Do you have either CurveFitting or Statistics Toolboxes? They've got much more sophisticated routines than using the venerable polyfit, polyval pair...particularly, the statistics on the fit, methods to return both predicted and residuals, etc., etc., etc., ...

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

채택된 답변

dpb
dpb 2022년 9월 5일
As per the above comment, if you have either of the toolboxes, I'd recommend using one of those routines instead, but to get by with what you've started with is pretty easy so far, anyways...
function [intercept, slope, resVar, fit, res] = fitLinearModel(x,y)
P = polyfit(x,y,1);
slope=P(1);
intercept=P(2);
fit=polyval(p,x);
res=y-fit;
resVar=var(res)*(numel(x)-1)/(numel(x)-2);
end
Since you didn't use polyval, I presume you didn't read/investigate either the examples or the 'See Also' links at <polyfit> that illustrate how to use the returned coefficients to make predictions. You'll get along MUCH faster if you read the documentation thoroughly before coming to the forum...

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Curve Fitting Toolbox에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by