2010-02-22

How to duplicate Matlab functionality

Since I am a total Matlab-n00b, I rather write a convoluted Python script instead of using the appropriate Matlab function. And here it is. A small script to compute the standard deviation of two vectors. I guess this would have been one Matlab command.


import sys
import scipy.io
import math

def computeStdDev(file, vec1, vec2):
data = scipy.io.loadmat(file, struct_as_record=True)
vector1 = data[vec1]
vector2 = data[vec2]
if len(vector1) != len(vector2):
print "Error: Vectors do not have matching lengths."
return
diff = vector1
N = len(diff)

for i in range(N):
diff[i] = vector1[i] - vector2[i]

mu = 0
for val in diff:
mu = mu + val
mu = mu / float(N)

sigma = 0
for i in range(N):
sigma = sigma + (diff[i] - mu)**2
sigma = math.sqrt(sigma / float(N))

print "mu: %f" % mu
print "sigma: %f" % sigma

if len(sys.argv) != 4:
print "Usage: %s file vector1 vector2" % sys.argv[0]
sys.exit(0)

computeStdDev(sys.argv[1], sys.argv[2], sys.argv[3])

3 comments:

  1. you should check out numpy and scipy :-)

    ReplyDelete
  2. Well, I already use scipy for loading theatlab files :)

    ReplyDelete
  3. http://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html :-)

    ReplyDelete