MATLAB: Linear Regression

I am trying to develop the most efficient method for finding the linear regression equation (y = mx + c) for the data set specified by array 2 by n.

Basically, I want to know what the value of Y is when X, for example, is 50.

My current method is poor:

inputData is my array 2 through n, with X in the first column and Y in the second.

x = 50 for i = 1 : size(inputData,1) % for every line in the inputData array if (inputData(i,1) < x + 5) | (inputData(i,1) > x - 5) % if we're within 5 of the specified X value arrayOfCloseYValues(i) = inputData(i, 2); % add the other position to the array end end y = mean(arrayOfCloseYValues) % take the mean to find Y 

As you can see, my above method just tries to find Y values โ€‹โ€‹that are within 5 of the given X value and get the average value. This is a terrible method, plus it requires adulthood to process.

I really need a reliable method of calculating linear regression for X and Y, so that I can find the value through the equation y = mx + c ...

PS. In my method above, I really predetermine memory and delete trailing zeros at the end, but I deleted this part for simplicity.

+4
source share
1 answer

The polyphite is fine, but I think you are a problem, it is a little easier. You have a 2 x n data array. Let say that column 1 is y, and column 2 is x, then:

 y = inputData(:,1); x = inputData(:,2); b = ones(size(inputData)); A = [xb]; c = A\y 

Should give you least squares regression for tilt and offset.

Here is another way to test it:

 x = transpose(0:10); y = 0.5*x + 1 + 0.1*randn(size(x)); % as a test, m = 0.5, b=1, and add some noise A = [x ones(size(x))]; c = A\y; yest = c(1)*x + c(2); plot(x,yest,x,y) legend('y_{est}','y') 

It should turn out: Estimated Y v Actual Y

+4
source

Source: https://habr.com/ru/post/1396886/


All Articles