Info

This question is closed. Reopen it to edit or answer.

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

1 view (last 30 days)
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 Comments
James Tursa
James Tursa on 21 Oct 2016
+1 Guillaume. Personally I never use length() ... I do these types of checks with some combination of size() and/or numel() outputs.
Guillaume
Guillaume on 22 Oct 2016
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.

Answers (1)

James Tursa
James Tursa on 21 Oct 2016
Edited: James Tursa on 21 Oct 2016
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 Comments
James Tursa
James Tursa on 21 Oct 2016
Edited: James Tursa on 21 Oct 2016
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 on 22 Oct 2016
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.

This question is closed.

Community Treasure Hunt

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

Start Hunting!