def __mul__(self, other): """interpret other and call one of the following self._mul_scalar() self._mul_vector() self._mul_multivector() self._mul_sparse_matrix() """ M,N = self.shape if isscalarlike(other): # scalar value return self._mul_scalar(other) if issparse(other): if self.shape[1] != other.shape[0]: raise ValueError('dimension mismatch') return self._mul_sparse_matrix(other) try: other.shape except AttributeError: # If it's a list or whatever, treat it like a matrix other = np.asanyarray(other) other = np.asanyarray(other) if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1: # dense row or column vector if other.shape != (N,) and other.shape != (N,1): raise ValueError('dimension mismatch') result = self._mul_vector(np.ravel(other)) if isinstance(other, np.matrix): result = np.asmatrix(result) if other.ndim == 2 and other.shape[1] == 1: # If 'other' was an (nx1) column vector, reshape the result result = result.reshape(-1,1) return result elif other.ndim == 2: ## # dense 2D array or matrix ("multivector") if other.shape[0] != self.shape[1]: raise ValueError('dimension mismatch') result = self._mul_multivector(np.asarray(other)) if isinstance(other, np.matrix): result = np.asmatrix(result) return result else: raise ValueError('could not interpret dimensions')
def sum(self, axis=None): """Sum the matrix over the given axis. If the axis is None, sum over both rows and columns, returning a scalar. """ # We use multiplication by an array of ones to achieve this. # For some sparse matrix formats more efficient methods are # possible -- these should override this function. m, n = self.shape if axis == 0: # sum over columns return np.asmatrix(np.ones((1, m), dtype=self.dtype)) * self elif axis == 1: # sum over rows return self * np.asmatrix(np.ones((n, 1), dtype=self.dtype)) elif axis is None: # sum over rows and columns return ( self * np.asmatrix(np.ones((n, 1), dtype=self.dtype)) ).sum() else: raise ValueError, "axis out of bounds"
def todense(self): return np.asmatrix(self.toarray())