4

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

基本上我想知道当 X 为 50 时 Y 的值是多少。

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

inputData 是我的 2 x 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

如您所见,我上面的方法只是尝试找到在给定 X 值 5 以内的 Y 值并获得平均值。这是一种糟糕的方法,而且处理起来绝对需要很长时间。

我真正需要的是一种稳健的方法来计算 X 和 Y 的线性回归,这样我就可以通过方程 y = mx + c 找到值...

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

4

1 回答 1

4

Polyfit 很好,但我认为你的问题有点简单。你有一个 2 xn 的数据数组。假设第 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')

应该让你: 估计 Y v 实际 Y

于 2012-02-16T17:57:59.967 回答