UP | HOME

Exercise 12

Mean of a vector

If we have a vector \(X\) containing \(n\) values, then the mean \(\bar{X}\) is:

\begin{equation} \bar{X} = \frac{1}{n} \sum_{i=1}^{N} \left( X_{i} \right) \end{equation}

In MATLAB, Python (NumPy) and R there are built-in functions for computing the mean of a vector. Conveniently, in all three languages the function is called mean().

In MATLAB:

x = [2,1,5,4,8,3,4,3];
mean(x)

ans =

    3.7500

In Python / NumPy: (started using ipython --pylab)

x = array([2,1,5,4,8,3,4,3], 'float')
mean(x)
Out[2]: 3.75

In R:

x <- c(2,1,5,4,8,3,4,3)
mean(x)
[1] 3.75

from scratch

Write a function called mymean() that computes the mean of a list of numbers. Do it from scratch, in other words don't use the built-in function mean().

solutions


Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License