Функция Numpy asmatrix() в Python создает матрицу, интерпретирующую данный ввод. В отличие от матричной функции, она не копирует введенные данные в виде матрицы или ndarray. numpy.asmatrix(data, dtype = None) возвращает матрицу, интерпретируя ввод как матрицу.
Что такое Numpy asmatrix()?
Функция NumPy asmatrix() используется для интерпретации данного ввода как матрицы.
Синтаксис
|
1 |
numpy.asmatrix(data, dtype=None) |
- data: (array_like)
Мы предоставляем вход в виде массива для преобразования его в матрицу.
- dtype:(data-type)
Тип данных результирующей матрицы, сформированной с помощью функции asmatrix, предоставляется по умолчанию, он совпадает с введенными данными.
Возвращаемое значение
Функция берет введенный массив и преобразует его в матрицу. Она не делает копию, если передается матрица или ndarray. Тип данных выходной матрицы совпадает с типом входного массива.
Пример:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
# app.py import numpy as np x = np.array([[1, 2], [3, 4]]) m = np.asmatrix(x) print(m) print('Manipulating the matrix formed via asmatrix function') x[0, 0] = 5 print(m) a = np.asmatrix(np.zeros((3, 1))) print(a) |
Вывод:
|
1 2 3 4 5 6 7 8 9 |
python3 app.py [[1 2] [3 4]] Manipulating the matrix formed via asmatrix function [[5 2] [3 4]] [[0.] [0.] [0.]] |
Программы с функцией asmatrix() в Python
Напишем программу, показывающую преобразование массива в матрицу и изменение элемента также на Python.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# app.py import numpy as np data = [] rm = input("Enter the rows:") cm = input("Enter the cols:") row = int(rm) col = int(cm) print("Enter the data rowise:") for i in range(row): for j in range(col): data.append(int(input())) a = np.array(data).reshape(row, col) print("as array: \n", a) c = np.asmatrix(a) print("as matrix: \n", c) cn = input("Enter the row of modified value:") cm = input("Enter the col of modified value:") cb = input("Enter the value to be modified in the matrix:") n = int(cn) m = int(cm) b = int(cb) a[n - 1, m - 1] = b print("as matrix after modifying value: \n", c) |
Вывод:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
python3 app.py Enter the rows:2 Enter the cols:2 Enter the data rowise: 2 2 2 2 as array: [[2 2] [2 2]] as matrix: [[2 2] [2 2]] Enter the row of modified value:1 Enter the col of modified value:1 Enter the value to be modified in the matrix:3 <class 'numpy.ndarray'> as matrix after modifying value: [[3 2] [2 2]] |
Давайте посмотрим другие варианты вывода.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
Value for parameter a=array([[1, 2],[3, 4]]) Enter the rows:2 Enter the cols:2 Enter the data rowise: 1 2 3 4 as array: array([[1, 2], [3, 4]])) as matrix: matrix([[1, 2], [3, 4]])) Enter the row of modified value:1 Enter the col of modified value:1 Enter the value to be modified in the matrix:10 As matrix after modifying value: matrix([[10, 2], [3, 4]])) Value for parameter a=array([[5, 6, 8, 4],[9, 7, 3, 1]]) Enter the rows:2 Enter the cols:4 Enter the data rowise: 5 6 8 4 9 7 3 1 as array: array([[5, 6, 8, 4], [9, 7, 3, 1]])) as matrix: matrix([[5, 6, 8, 4], [9, 7, 3, 1]])) Enter the row of modified value:2 Enter the col of modified value:3 Enter the value to be modified in the matrix:2 As matrix after modifying value: matrix([[5, 6, 8, 4], [9, 7, 2, 1]])) Value for parameter a=array([[11],[10]]) Enter the rows:1 Enter the cols:1 Enter the data rowise: 11 10 as array: array([[11], [10]])) as matrix: matrix([[11], [10]])) Enter the row of modified value:1 Enter the col of modified value:1 Enter the value to be modified in the matrix:8 As matrix after modifying value: matrix([[8], [10]])) Value for parameter a=array([[15, 16, 18],[19, 17, 20],[11, 12, 13]) Enter the rows:3 Enter the cols:3 Enter the data rowise: 15 16 18 19 17 20 11 12 13 as array: array([[15, 16, 18], [19, 17, 20], [11, 12, 13]])) as matrix: matrix([[15, 16, 18], [19, 17, 20], [11, 12, 13]])) Enter the row of modified value:3 Enter the col of modified value:3 Enter the value to be modified in the matrix:50 As matrix after modifying value: matrix([[15, 16, 18], [19, 17, 20], [11, 12, 50]])) |
Здесь данные для матрицы были предоставлены пользователем, а введенные данные преобразованы в матрицу. Пользователь предоставляет данные для матрицы, а также размер матрицы. Это не делает копию, как матричная функция.
После преобразования входных данных в матрицу мы изменяем значение в месте, введенном пользователем, с введенным значением.
Заключение

Функция asmatrix() интерпретирует ввод как матрицу. Это не то же самое, что матрица, потому что asmatrix не делает копию, если вход уже является матрицей или ndarray. Эквивалент матрице (data, copy=False).
