MATLAB Code Examples
function mean = stats(x)
if ~isvector(x)
error(‘Input must be a vector’)
end
mean = sum(x)/length(x);
end
function [mean, sdev] = stats(x)
if ~isvector(x)
error(‘Input must be a vector’)
end
len = length(x);
mean = sum(x)/len;
sdev = sqrt(sum((x-mean).^2/len));
end
Python Code Examples
import numpy as np
# Function definition is here
def stats( my_array ):
"This calculates the mean of the input array"
mean = np.sum(my_array)/np.size(my_array)
return mean
# Now you can call stats function
m = stats([4,5,6])
print(m)
Exercises
- Write a function that calculates the factorial for the input value..
- Write a function that calculates the factorial for each value of an input vector, and returns a vector of results.
- Write a function that takes an input matrix, and calculates the average value of each row (or – if instructed by an optional argument – the average value of each column) and returns a vector containing the results
- Package your functions from these exercises into a custom Python module.