UP | HOME

Exercise 16 solutions

Table of Contents

-—

Python

e16.py

from numpy import loadtxt, mean
filename = "e16data.csv"
d = loadtxt(fname=filename,dtype=float,delimiter=",")
mean1 = mean(d[:,0])
mean2 = mean(d[:,1])

MATLAB / Octave

e16.m

filename = 'e16data.csv';
d = load(filename);
mean1 = mean(d(:,1));
mean2 = mean(d(:,2));

R

e16.R

filename <- "e16data.csv"
d <- read.table(filename, sep=",", col.name=c("pizza","banana"))
mean1 <- mean(d[,1])
mean2 <- mean(d[,2])

C

e16.c

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

#include <stdio.h>

void showvec(double v[], int rows) {
        int i,j;
        for (i=0; i<rows; i++) {
                printf("%f\n", v[i]);
        }
}

double meanvec(double v[], int rows) {
        int i;
        double m = 0.0;
        for (i=0; i<rows; i++) {
                m += v[i];
        }
        m = m / (double)rows;
        return m;
}

int main(int argc, char *argv[]) {
        FILE *fid = fopen("e16data.csv", "r");
        int rows = 10;
        double v1[rows], v2[rows];
        int i;
        for (i=0; i<rows; i++) {
                fscanf(fid, "%lf,%lf", &(v1[i]), &(v2[i]));
        }
        fclose(fid);
        showvec(v1, rows);
        showvec(v2, rows);
        double m1 = meanvec(v1, rows);
        double m2 = meanvec(v2, rows);
        printf("mean1 = %f\nmean2 = %f\n", m1, m2);
        return 0;
}

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