I am a data scientist working on time series forecasting (using R and Python 3) at the London Ambulance Service NHS Trust. I earned my PhD in cognitive neuroscience at the University of Glasgow working with fmri data and neural networks. I favour linux machines, and working in the terminal with Vim as my editor of choice.
Summing all the values in each column, or in each row, of a matrix is a common operation. We can achieve it my multiplying the matrix with a vector of ones: multiplying on the left side will sum the columns, multiplying on the right will sum the rows.
In our function, we will always multiply on the left, and therefore transpose the matrix in the case that we want the sum the rows. If a vector is passed, we always sum the elements:
We create a matrix, call the sum method twice with a different axis as an argument and print the results:
Now that we have a function to sum, we can divide the result by the number of elements that went into the sum to obtain the mean. We transpose the vector from a row to a column in the case that we computed the mean across the rows of the matrix:
We create a matrix, call the mean method twice with a different axis as an argument and print the results (we only print 2 decimal places in one case to make it look pretty):
Outputs:
back to project main page
back to home