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

조회 수: 2 (최근 30일)
Panji Nurhusni
Panji Nurhusni 2018년 4월 17일
편집: Stephen23 2018년 4월 17일
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
Stephen23
Stephen23 2018년 4월 17일
편집: Stephen23 2018년 4월 17일
>> 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!

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2018년 4월 17일
편집: KSSV 2018년 4월 17일
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
Panji Nurhusni
Panji Nurhusni 2018년 4월 17일
편집: Panji Nurhusni 2018년 4월 17일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by