UP | HOME

Exercise 12 solutions

Table of Contents


Python

e12.py

from numpy import array

# define the mymean() function
#
def mymean(x):
    n = len(x)
    m = 0
    for i in range(n):
        m = m + x[i]
    m = m / n
    return m

# test the function
#
a = array([1,2,3,4,5], "float")
am = mymean(a)
print str(am)

MATLAB / Octave

mymean.m

function m = mymean(x)
  n = length(x);
  m = 0;
  for i = 1:n
    m = m + x(i);
  end
  m = m / n;

e12.m

a = [1,2,3,4,5];
am = mymean(a);
disp(num2str(am));

R

e12.R

# define the mymean() function
#
mymean <- function(x) {
    n <- length(x)
    m <- 0
    for (i in seq(n)) {
	m <- m + x[i]
    }
    m <- m / n
    m
}

# test the function
#
a <- c(1,2,3,4,5)
am <- mymean(a)
cat(am,"\n")

C

e12.c

// compile with: gcc -o e12 e12.c

#include <stdio.h>
#include <stdlib.h> // for malloc

double mymean(double x[], int xlen) {
  double out = 0;
  int i;
  for (i=0; i<xlen; i++) {
    out += x[i];
  }
  out = out / xlen;
  return out;
}

int main(int argc, char const *argv[])
{
  // define our array x on the stack
  double x[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
  int xlen = 5;
  double xmean = mymean(x, xlen);
  printf("the mean of x is %.3f\n", xmean);

  // or we can define it on the heap
  int ylen = 5;
  double *y  = malloc(ylen * sizeof(double));
  y[0] = 1.0;
  y[1] = 2.0;
  y[2] = 3.0;
  y[3] = 4.0;
  y[4] = 5.0;
  double ymean = mymean(y, ylen);
  printf("the mean of y is %.3f\n", ymean);  
  free(y);

  return 0;
}

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