numpy矩阵基本操作总结

import numpy as np;
import math;

#构造矩阵
m = np.mat([[1,2,3,4],[2,2,3,4],[3,2,3,4],[4,2,3,4]]);
print(m);
#取第i行,从0开始计数
row1 = m[0];
print(row1);
#取[i,j]元素,从0开始计数,如果是:这种形式那么是从i开始包含i,到j截至不包含j
item1 = m[0, 1];
print(item1);
item2 = m[0, :];
print(item2);
item3 = m[0:2, 0:3];
print(item3);
#矩阵运算
n = np.mat([[5,5,5,5],[2,2,2,2]]);
result = m * n.transpose();
print(result);
addRes = m + m;
print(addRes);
subRes = m - m;
print(subRes);
powRes = np.power(m, 2);
print(powRes);
logRes = np.log(m);
print(logRes);

#求矩阵的行数和列数
rowM, colM = np.shape(m);
rowN = np.shape(n)[0];
colN = np.shape(n)[1];
print(rowN, colN);

zeros = np.zeros((4, 3));
print(zeros);

ones = np.ones((4, 3));
print(ones);

constantMat = np.full((4, 3), 7);
print(constantMat);
#创建单位矩阵
I = np.eye(2);
print(I);
#输出随机元素构成的矩阵
randomMat = np.random.random((2, 3));
print(randomMat);
#矩阵拼接按行拼接row_stack,和按列拼接column_stack
mn = np.row_stack((m, n));
print(mn);



你可能感兴趣的:(python,numpy)