MATLAB Answers

Amitdyuti
1

Mean of squares of first nn positive integers.

Asked by Amitdyuti
on 24 Jul 2015
Latest activity Commented on by Ali Tajik on 23 Jan 2017
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 Comments

You could just say
mean_squares = @(nn) (nn+1).*(2*nn+1)/6;
function O = odd_rms(n)
n = n*2-1;
O = [1:2:n];
O = O.^2;
O = sum(O)/n;
O = sqrt(O);
it did not work for 2 when you check it by grader

Sign in to comment.

Tags

No tags entered yet.

3 Answers

Answer by Matt J
on 24 Jul 2015
 Accepted Answer

Looks fine to me, but you should also be aware that there is a closed form formula
mm = (nn+1)*(2*nn+1)/6

  0 Comments

Sign in to comment.


Answer by Harsheel
on 24 Jul 2015

the code looks correct, seems like you're passing a character rather than an integer.
>> mean_squares('5') % incorrect
>> mean_squares(5) %correct

  0 Comments

Sign in to comment.


Answer by Amitdyuti
on 24 Jul 2015

Thank You for the answers. But after posting the question,when I re-executed the function, voila! It ran successfully.
Sorry for the inconvenience.

  0 Comments

Sign in to comment.