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

8 views (last 30 days)

Show older comments

Hi I'm trying to make a function that

- Gives me a vector of fitted values based off of a linear model of y on x
- 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 Comment

dpb
on 5 Sep 2022

### Accepted Answer

dpb
on 5 Sep 2022

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 Comments

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!