Info

此问题已关闭。 请重新打开它进行编辑或回答。

Why is it saying that I am exceeding the matrix dimensions for the sum_xy when x(2) is clearly a part of the vector that I give

2 次查看(过去 30 天)
function [ y ] = linregress( XDATA, YDATA )
%linear regression function using given algorithm
% Detailed explanation goes here
x = XDATA;
y = YDATA;
m = length (y);
n = length(x);
if m~= n
error('x and y do not have equal number of data points')
end
sum_xy = 0;
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
i = 0;
while i <= n
i=i+1
sum_xy = sum_xy + x(i)*y(i)
sum_x = sum_x + x(i);
sum_y = sum_y + y(i);
sum_x2 = sum_x2 + (x(i))^2;
a1 = (n * sum_xy - sum_x * sum_y)/(n * sum_x2 - (sum_x)^2);
a0= (1/n) * sum_y - (a1/n)*sum_x;
y = (y(i) - a0 - a1 * x(i))^2;
end
end
  3 个评论
James Tursa
James Tursa 2016-10-21
+1 Guillaume. Personally I never use length() ... I do these types of checks with some combination of size() and/or numel() outputs.
Guillaume
Guillaume 2016-10-22
Indeed, size and numel are much better. In this case, however, I would use:
validateattributes(XDATA, {'numeric'}, {'vector', 'finite'}, 1);
validateattributes(YDATA, {'numeric'}, {'vector', 'finite', 'numel', numel(XDATA)}, 2);
instead of the if test.
I think the above covers all the assumptions in the code.

回答(1 个)

James Tursa
James Tursa 2016-10-21
编辑:James Tursa 2016-10-21
You want to change your while test to this:
while i < n
because the next line increments i. If you allow i to be n after this check then you allow i to be n+1 inside the loop, hence the error. (A for-loop might be more appropriate here rather than a while-loop with an increment.)
  3 个评论
James Tursa
James Tursa 2016-10-21
编辑:James Tursa 2016-10-21
Sorry, I should have looked more closely. You are using y for two different things and they are clashing. The first use is for your input data:
y = YDATA;
:
sum_xy = sum_xy + x(i)*y(i)
:
And the second use is for your output variable:
function [ y ] = linregress( XDATA, YDATA )
:
y = (y(i) - a0 - a1 * x(i))^2;
After the first iteration this line has wiped out the y that you were using for your input data. You need to change the name of one of these, e.g. your output variable.
function [ Y ] = linregress( XDATA, YDATA )
:
Y = (y(i) - a0 - a1 * x(i))^2;
Guillaume
Guillaume 2016-10-22
Well, there is absoltely no point to these two lines:
x = XDATA;
y = YDATA;
Simply, use XDATA and YDATA for the rest of the code. Why rename them, what's wrong with their original name? If you hadn't done that you wouldn't have that 2nd (3rd?) bug.
One other minor bug is that the calculation of a0, a1 and the output y should be after the loop. It's not critical, as it is it means you're calculting intermediate values that are never used and serve no purpose.

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by