Mean of squares of first nn positive integers.

조회 수: 1 (최근 30일)
Amitdyuti
Amitdyuti 2015년 7월 24일
댓글: Ali Tajik 2017년 1월 23일
Write a function called mean_squares that returns mm, which is the mean of the squares of the first nn positive integers, where nn is a positive integer and is the only input argument. For example, if nn is 5, your function needs to compute the average of the numbers 1, 4, 9, 16, and 25. You may use any built-in functions including, for example, sum.
function mm = mean_squares (nn)
sqr = (1:nn).^2; %ERROR
total = sum(sqr);
mm = total/nn;
end
I wrote the above code. In line 2, I got the following error: "For colon operator with char operands, first and last operands must be char."
However,the code if executed in the command window, runs fine.
  댓글 수: 3
Duddela Sai Prashanth
Duddela Sai Prashanth 2016년 12월 23일
function O = odd_rms(n)
n = n*2-1;
O = [1:2:n];
O = O.^2;
O = sum(O)/n;
O = sqrt(O);
Ali Tajik
Ali Tajik 2017년 1월 23일
it did not work for 2 when you check it by grader

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

채택된 답변

Matt J
Matt J 2015년 7월 24일
Looks fine to me, but you should also be aware that there is a closed form formula
mm = (nn+1)*(2*nn+1)/6

추가 답변 (2개)

Harsheel
Harsheel 2015년 7월 24일
the code looks correct, seems like you're passing a character rather than an integer.
>> mean_squares('5') % incorrect
>> mean_squares(5) %correct

Amitdyuti
Amitdyuti 2015년 7월 24일
Thank You for the answers. But after posting the question,when I re-executed the function, voila! It ran successfully.
Sorry for the inconvenience.

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by