MATLAB:线性回归

时间:2012-02-16 17:06:45

标签: matlab linear-regression

我正在尝试找出最有效的方法来找到数据集的线性回归方程(y = mx + c),给定2乘n数组。

基本上我想知道当X是例如50时Y的值是什么。

我目前的方法还有很多不足之处:

inputData是我的2乘n数组,第一列是X,第二列是Y。

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

正如您所看到的,我的上述方法只是试图找到Y的值,它们在给定X值的5以内并获得平均值。这是一种可怕的方法,加上它需要绝对的年龄来处理。

我真正需要的是一种用于计算X和Y的线性回归的稳健方法,因此我可以通过等式y = mx + c找到该值...

PS。在上面的方法中,我确实预先分配了内存并在结尾处删除了尾随的零,但为了简单起见,我删除了这部分。

1 个答案:

答案 0 :(得分:4)

Polyfit很好,但我认为你的问题有点简单。你有一个2 x n数据数组。假设第1列为y,第2列为x,则为:

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

应该为斜率和偏移量提供最小二乘回归。

这是测试它的另一种方法:

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')

应该得到你: Estimated Y v Actual Y