Computing a numerical value but gets output of 2 columns array?

2 views (last 30 days)
Hi. I'm new to Matlab coming from python. My prof requires us to use Matlab as the main tool for the course. I'm currently making an algorithm to compute the least square value of the given data.
I'm currently getting a problem where I compute a numerical value but somehow the output shows me a 2 columns array. In this code, I'm talking about the variable a1a, a1b, a0, avgX and avgY. I understand why a0 gives me an array because the input (avgX and avgY) are an array. But, on the other hand, the inputs for a1a, a1b, avgX and avgY are integers/numerical values (based on the workspace shows), so why on the earth they would somehow become a 2 column array?
What did I do wrong? Can someone point me? I know my Matlab knowledge is quite basic, but this abstract problem frustrates me much!
In case of someone wonders, I previously use a '/' sign (without a dot sign on the front) for avgX and avgY equation, but it always gave me an error so I decided to replace it with a './' sign.
arrX = [0 2 4 6 9 11 12 15 17 19];
arrY = [5 6 7 6 9 8 7 10 12 12];
n = size(arrX);
sumX = 0;
sumY = 0;
sumXY = 0;
sumX2 = 0;
for iter = 1 : 10;
sumX = sumX + arrX(iter);
sumY = sumY + arrY(iter);
sumXY = sumXY + (arrX(iter)*arrY(iter));
sumX2 = sumX2 + (arrX(iter)^2);
end;
sum2X = sumX^2;
avgX = sumX./n;
avgY = sumY./n;
a1a = (n*sumXY)-(sumX*sumY);
a1b = (n*sumX2)-sum2X;
a1 = a1a/a1b;
a0 = avgY-(a1*avgX);
  1 Comment
Stephen23
Stephen23 on 17 Apr 2018
Edited: Stephen23 on 17 Apr 2018
>> arrX = [0 2 4 6 9 11 12 15 17 19];
>> size(arrX)
ans =
1 10
Always read the documentation for every operator and function that you use, no matter how trivial you think they are. Especially if you have experience in some other programming language!

Sign in to comment.

Accepted Answer

KSSV
KSSV on 17 Apr 2018
Edited: KSSV on 17 Apr 2018
n = size(arrX) ;

This is not correct.....use:

n = size(arrX,2) ; or 
n = length(arrX) ;

Note that, you can use in built functions....to get what you want. Read about sum, mean etc,.

  2 Comments
Panji Nurhusni
Panji Nurhusni on 17 Apr 2018
Edited: Panji Nurhusni on 17 Apr 2018
Thanks, dude! I can't believe the problem is on the 'n' variable! The first result of length counting function is always this 'size' function, so I thought this is the matlab's length function and I didn't know there was another option.
Regarding the built in function, my prof asks us to use the built in function as less as possible. So we need to build up the sum, mean, etc function by ourselves.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!