Skip to content

Instantly share code, notes, and snippets.

@vrld
Last active May 6, 2016 11:55
Show Gist options
  • Save vrld/4d686941caf0b34894791eddd3841214 to your computer and use it in GitHub Desktop.
Save vrld/4d686941caf0b34894791eddd3841214 to your computer and use it in GitHub Desktop.
def covar_2d(e, s):
"""Returns a 2D covariance matrix with main diagonal in direction e and second diagonal perpendicular to e with proportional length s.
Params:
-------
e: array-like
Direction of the main diagonal.
s: float
Proportional scale of the second diagonal.
Returns:
--------
cov : ndarray
A psd matrix with the properties defined above.
Example:
--------
>>> covar_2d([1,5], .3)
matrix([[ 0.32692308, 0.13461538],
[ 0.13461538, 0.97307692]])
>>> X = np.random.multivariate_normal([0,0], covar_2d([1,5], .3), 10000)
>>> pylab.scatter(X[:,0], X[:,1])
"""
Q = np.matrix([e[:2], [e[1], -e[0]]])
return Q * np.matrix([[1, 0], [0, s]]) * np.linalg.inv(Q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment