Richard
Richard

Reputation: 61289

Numpy Element-wise Standard Deviation

Say I have n 2-dimensional matricies M1, M2, M3, ... all with the same dimensions.

Is there an efficient way to produce an output matrix MR where each element in MR corresponds to the standard deviation of the elements in that position in M1, M2, M3, ...

An example of the operation follows:

       1 4 5   8 2 3   -1 8 2      4.73  3.06  1.53
stdev( 3 9 2,  2 1 0,   0 3 1 ) =  1.53  4.16  1.00
       7 1 2   8 3 1    9 5 8      1.00  2.00  3.79

To clarify: the top left element of the resultant matrix is calculated as follows:

stdev(1,8,-1) = 4.7258

Whereas the bottom left element is calculated as:

stdev(7,8,9) = 1.00

If this is not a way to do this with built-in operators in one go is there an efficient alternative?

Here are the test matrices:

a=numpy.array( [[1,4,5],[3,9,2],[7,1,2]])
b=numpy.array( [[8,2,3],[2,1,0],[8,3,1]])
c=numpy.array([[-1,8,2],[0,3,1],[9,5,8]])

Upvotes: 3

Views: 3081

Answers (2)

lejlot
lejlot

Reputation: 66805

numpy is your friend

import numpy as np
print np.std((a,b,c), axis=0, ddof=1)

for provided matrices it gives

array([[ 4.72581563,  3.05505046,  1.52752523],
       [ 1.52752523,  4.163332  ,  1.        ],
       [ 1.        ,  2.        ,  3.7859389 ]])

as expected

Upvotes: 6

tillsten
tillsten

Reputation: 14878

First put your data into one array:

d = np.dstack((a,b,c))

Than take the std along the thrid axies:

np.std(d, 2, ddof=1)

Upvotes: 1

Related Questions