📜  Python| numpy matrix.max()(1)

📅  最后修改于: 2023-12-03 14:46:21.137000             🧑  作者: Mango

Python | numpy matrix.max()

The matrix.max() function in the numpy library is used to find the maximum value in a matrix or an array-like object. It returns the maximum element along a specified axis or the maximum element in the entire matrix if no axis is specified.

Syntax:
numpy.matrix.max(axis=None, out=None)

Parameters:

  • axis (optional): Axis along which the maximum values are extracted. By default, it considers the maximum value of the flattened matrix.
  • out (optional): Alternate output array in which to place the result. It must have the same shape and buffer length as the expected output.

Returns:

  • If axis is provided, it returns an array with the maximum values along the specified axis.
  • If axis is not provided, it returns a single maximum value from the entire matrix.
Examples:
Example 1: Find maximum element
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Find the maximum element in the matrix
max_value = matrix.max()

print("Maximum element in the matrix:", max_value)

Output:

Maximum element in the matrix: 9
Example 2: Find maximum element along axis
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Find the maximum elements along the rows (axis=0)
max_values_rows = matrix.max(axis=0)

# Find the maximum elements along the columns (axis=1)
max_values_columns = matrix.max(axis=1)

print("Maximum elements along rows:", max_values_rows)
print("Maximum elements along columns:", max_values_columns)

Output:

Maximum elements along rows: [7 8 9]
Maximum elements along columns: [3 6 9]
Example 3: Store result in an alternate array
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.zeros((matrix.shape[0],))

# Find the maximum elements along columns and store them in the result array
matrix.max(axis=1, out=result)

print("Maximum elements along columns:", result)

Output:

Maximum elements along columns: [3. 6. 9.]

In the above example, an alternate output array result is used to store the maximum elements along columns. The shape and buffer length of the result array must match the expected output.