def norm(x, y=2): """ Norm of a matrix or a vector according to Matlab. The description is taken from Matlab: For matrices... NORM(X) is the largest singular value of X, max(svd(X)). NORM(X,2) is the same as NORM(X). NORM(X,1) is the 1-norm of X, the largest column sum, = max(sum(abs((X)))). NORM(X,inf) is the infinity norm of X, the largest row sum, = max(sum(abs((X')))). NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))). NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'. For vectors... NORM(V,P) = sum(abs(V).^P)^(1/P). NORM(V) = norm(V,2). NORM(V,inf) = max(abs(V)). NORM(V,-inf) = min(abs(V)). """ x = numerix.asarray(x) if MLab.rank(x) == 2: if y == 2: return MLab.max(MLab.svd(x)[1]) elif y == 1: return MLab.max(MLab.sum(numerix.absolute((x)))) elif y == 'inf': return MLab.max(MLab.sum(numerix.absolute((MLab.transpose(x))))) elif y == 'fro': return MLab.sqrt( MLab.sum( MLab.diag(numerix.matrixmultiply(MLab.transpose(x), x)))) else: verbose.report_error('Second argument not permitted for matrices') return None else: if y == 'inf': return MLab.max(numerix.absolute(x)) elif y == '-inf': return MLab.min(numerix.absolute(x)) else: return numerix.power( MLab.sum(numerix.power(numerix.absolute(x), y)), 1 / float(y))
def norm(x,y=2): """ Norm of a matrix or a vector according to Matlab. The description is taken from Matlab: For matrices... NORM(X) is the largest singular value of X, max(svd(X)). NORM(X,2) is the same as NORM(X). NORM(X,1) is the 1-norm of X, the largest column sum, = max(sum(abs((X)))). NORM(X,inf) is the infinity norm of X, the largest row sum, = max(sum(abs((X')))). NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))). NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'. For vectors... NORM(V,P) = sum(abs(V).^P)^(1/P). NORM(V) = norm(V,2). NORM(V,inf) = max(abs(V)). NORM(V,-inf) = min(abs(V)). """ x = numerix.asarray(x) if MLab.rank(x)==2: if y==2: return MLab.max(MLab.svd(x)[1]) elif y==1: return MLab.max(MLab.sum(numerix.absolute((x)))) elif y=='inf': return MLab.max(MLab.sum(numerix.absolute((MLab.transpose(x))))) elif y=='fro': return MLab.sqrt(MLab.sum(MLab.diag(numerix.matrixmultiply(MLab.transpose(x),x)))) else: verbose.report_error('Second argument not permitted for matrices') return None else: if y == 'inf': return MLab.max(numerix.absolute(x)) elif y == '-inf': return MLab.min(numerix.absolute(x)) else: return numerix.power(MLab.sum(numerix.power(numerix.absolute(x),y)),1/float(y))