0

I want to convert the following Matlab code to the equivalent in Python:

M.*((S*U)./max(realmin, M*(U'*U)))

where:

S: n*n
M: n*m
U: n*m

I have done it by the following code:

x = (max(-sys.maxint, np.matmul(M, np.matmul(np.transpose(U), U))))
M = np.dot(M, ((np.matmul(S, U)) / x))

but I got the following error:

x = (max(-sys.maxint, np.matmul(M, np.matmul(np.transpose(U), U))))
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

Would you please help me how I can convert the Matlab code to Python.

Somaye
  • 114
  • 1
  • 3
  • 11
Mehdi
  • 117
  • 1
  • 6
  • possible duplicate of https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous – Elliott Beach Jan 03 '18 at 17:45
  • 1
    Possible duplicate of [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – Robert Columbia Jan 03 '18 at 17:50
  • though the errors are the same but i think the problem for me is raised because of wrong conversion of matlab code and the privided links cannot help me – Mehdi Jan 03 '18 at 19:48
  • `M * ( S @ U) / np.maximum(numpy.finfo(float).tiny, M @ U.T @ U))` – percusse Jan 04 '18 at 00:45

1 Answers1

1

Matlab's max(a, b) is a broadcasted elementwise maximum operation. Python's max(a, b) isn't. Python's max doesn't understand arrays, and you shouldn't use it on arrays.

For a broadcasted elementwise maximum, you want numpy.maximum:

numpy.maximum(whatever, whatever)

Also, Matlab's realmin is the smallest positive normalized double-precision floating-point number, while Python's sys.maxint is a large negative int (and also nonexistent on Python 3). That's probably not what you want. The equivalent to Matlab's realmin would be

sys.float_info.min

or

numpy.finfo(float).tiny

(numpy.finfo(float).min is a different thing.)

user2357112
  • 260,549
  • 28
  • 431
  • 505