master
Per.Andreas.Brodtkorb 11 years ago
parent 31f80c5798
commit 5c84825641

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,15 +1,16 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Created on Tue Apr 17 13:59:12 2012 Created on Tue Apr 17 13:59:12 2012
@author: pab @author: pab
""" """
import numpy as np import numpy as np
def magic(n):
ix = np.arange(n)+1 def magic(n):
J, I = np.meshgrid(ix,ix) ix = np.arange(n) + 1
A = np.mod(I+J-(n+3)/2,n) J, I = np.meshgrid(ix, ix)
B = np.mod(I+2*J-2,n) A = np.mod(I + J - (n + 3) / 2, n)
M = n*A + B + 1 B = np.mod(I + 2 * J - 2, n)
return M M = n * A + B + 1
return M

@ -1,133 +1,136 @@
import numpy as np import numpy as np
def meshgrid(*xi, **kwargs):
"""
Return coordinate matrices from one or more coordinate vectors. def meshgrid(*xi, **kwargs):
"""
Make N-D coordinate arrays for vectorized evaluations of Return coordinate matrices from one or more coordinate vectors.
N-D scalar/vector fields over N-D grids, given
one-dimensional coordinate arrays x1, x2,..., xn. Make N-D coordinate arrays for vectorized evaluations of
N-D scalar/vector fields over N-D grids, given
Parameters one-dimensional coordinate arrays x1, x2,..., xn.
----------
x1, x2,..., xn : array_like Parameters
1-D arrays representing the coordinates of a grid. ----------
indexing : 'xy' or 'ij' (optional) x1, x2,..., xn : array_like
cartesian ('xy', default) or matrix ('ij') indexing of output 1-D arrays representing the coordinates of a grid.
sparse : True or False (default) (optional) indexing : 'xy' or 'ij' (optional)
If True a sparse grid is returned in order to conserve memory. cartesian ('xy', default) or matrix ('ij') indexing of output
copy : True (default) or False (optional) sparse : True or False (default) (optional)
If False a view into the original arrays are returned in order to If True a sparse grid is returned in order to conserve memory.
conserve memory. Please note that sparse=False, copy=False will likely copy : True (default) or False (optional)
return non-contiguous arrays. Furthermore, more than one element of a If False a view into the original arrays are returned in order to
broadcasted array may refer to a single memory location. If you conserve memory. Please note that sparse=False, copy=False will likely
need to write to the arrays, make copies first. return non-contiguous arrays. Furthermore, more than one element of a
broadcasted array may refer to a single memory location. If you
Returns need to write to the arrays, make copies first.
-------
X1, X2,..., XN : ndarray Returns
For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` , -------
return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij' X1, X2,..., XN : ndarray
or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy' For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
with the elements of `xi` repeated to fill the matrix along return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
the first dimension for `x1`, the second for `x2` and so on. or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
with the elements of `xi` repeated to fill the matrix along
Notes the first dimension for `x1`, the second for `x2` and so on.
-----
This function supports both indexing conventions through the indexing keyword Notes
argument. Giving the string 'ij' returns a meshgrid with matrix indexing, -----
while 'xy' returns a meshgrid with Cartesian indexing. The difference is This function supports both indexing conventions through the indexing
illustrated by the following code snippet: keyword argument. Giving the string 'ij' returns a meshgrid with matrix
indexing, while 'xy' returns a meshgrid with Cartesian indexing. The
xv, yv = meshgrid(x, y, sparse=False, indexing='ij') difference is illustrated by the following code snippet:
for i in range(nx):
for j in range(ny): xv, yv = meshgrid(x, y, sparse=False, indexing='ij')
# treat xv[i,j], yv[i,j] for i in range(nx):
for j in range(ny):
xv, yv = meshgrid(x, y, sparse=False, indexing='xy') # treat xv[i,j], yv[i,j]
for i in range(nx):
for j in range(ny): xv, yv = meshgrid(x, y, sparse=False, indexing='xy')
# treat xv[j,i], yv[j,i] for i in range(nx):
for j in range(ny):
See Also # treat xv[j,i], yv[j,i]
--------
index_tricks.mgrid : Construct a multi-dimensional "meshgrid" See Also
using indexing notation. --------
index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
using indexing notation. using indexing notation.
index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
Examples using indexing notation.
--------
>>> nx, ny = (3, 2) Examples
>>> x = np.linspace(0, 1, nx) --------
>>> y = np.linspace(0, 1, ny) >>> nx, ny = (3, 2)
>>> xv, yv = meshgrid(x, y) >>> x = np.linspace(0, 1, nx)
>>> xv >>> y = np.linspace(0, 1, ny)
array([[ 0. , 0.5, 1. ], >>> xv, yv = meshgrid(x, y)
[ 0. , 0.5, 1. ]]) >>> xv
>>> yv array([[ 0. , 0.5, 1. ],
array([[ 0., 0., 0.], [ 0. , 0.5, 1. ]])
[ 1., 1., 1.]]) >>> yv
>>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays array([[ 0., 0., 0.],
>>> xv [ 1., 1., 1.]])
array([[ 0. , 0.5, 1. ]]) >>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays
>>> yv >>> xv
array([[ 0.], array([[ 0. , 0.5, 1. ]])
[ 1.]]) >>> yv
array([[ 0.],
`meshgrid` is very useful to evaluate functions on a grid. [ 1.]])
>>> x = np.arange(-5, 5, 0.1) `meshgrid` is very useful to evaluate functions on a grid.
>>> y = np.arange(-5, 5, 0.1)
>>> xx, yy = meshgrid(x, y, sparse=True) >>> x = np.arange(-5, 5, 0.1)
>>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2) >>> y = np.arange(-5, 5, 0.1)
>>> xx, yy = meshgrid(x, y, sparse=True)
>>> import matplotlib.pyplot as plt >>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2)
>>> h = plt.contourf(x,y,z)
""" >>> import matplotlib.pyplot as plt
copy_ = kwargs.get('copy', True) >>> h = plt.contourf(x,y,z)
args = np.atleast_1d(*xi) """
ndim = len(args) copy_ = kwargs.get('copy', True)
args = np.atleast_1d(*xi)
if not isinstance(args, list) or ndim<2: ndim = len(args)
raise TypeError('meshgrid() takes 2 or more arguments (%d given)' % int(ndim>0))
if not isinstance(args, list) or ndim < 2:
sparse = kwargs.get('sparse', False) raise TypeError(
indexing = kwargs.get('indexing', 'xy') 'meshgrid() takes 2 or more arguments (%d given)' % int(ndim > 0))
s0 = (1,)*ndim sparse = kwargs.get('sparse', False)
output = [x.reshape(s0[:i] + (-1,) + s0[i + 1::]) for i, x in enumerate(args)] indexing = kwargs.get('indexing', 'xy')
shape = [x.size for x in output] s0 = (1,) * ndim
output = [x.reshape(s0[:i] + (-1,) + s0[i + 1::])
if indexing == 'xy': for i, x in enumerate(args)]
# switch first and second axis
output[0].shape = (1, -1) + (1,)*(ndim - 2) shape = [x.size for x in output]
output[1].shape = (-1, 1) + (1,)*(ndim - 2)
shape[0], shape[1] = shape[1], shape[0] if indexing == 'xy':
# switch first and second axis
if sparse: output[0].shape = (1, -1) + (1,) * (ndim - 2)
if copy_: output[1].shape = (-1, 1) + (1,) * (ndim - 2)
return [x.copy() for x in output] shape[0], shape[1] = shape[1], shape[0]
else:
return output if sparse:
else: if copy_:
# Return the full N-D matrix (not only the 1-D vector) return [x.copy() for x in output]
if copy_: else:
mult_fact = np.ones(shape, dtype=int) return output
return [x * mult_fact for x in output] else:
else: # Return the full N-D matrix (not only the 1-D vector)
return np.broadcast_arrays(*output) if copy_:
mult_fact = np.ones(shape, dtype=int)
return [x * mult_fact for x in output]
def ndgrid(*args, **kwargs): else:
""" return np.broadcast_arrays(*output)
Same as calling meshgrid with indexing='ij' (see meshgrid for
documentation).
""" def ndgrid(*args, **kwargs):
kwargs['indexing'] = 'ij' """
return meshgrid(*args, **kwargs) Same as calling meshgrid with indexing='ij' (see meshgrid for
documentation).
if __name__ == '__main__': """
import doctest kwargs['indexing'] = 'ij'
doctest.testmod() return meshgrid(*args, **kwargs)
if __name__ == '__main__':
import doctest
doctest.testmod()

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save