
1、导入基本函数库
import numpy as np
2、获取矩阵元素字节数
a=np.array([1,2,3],dtype=np.float32)
a.itemsize
output: 4
3、获取数组维数A.shape
例如
a=np.array([[1,2,3],[4,5,6]]); a.shape output:(2,3)
4、选取某一行或某一列元素,
注意numpy中数组起始坐标是0开始的,跟matlab中有区别。matlab中是从1开始的。
python中列表[start,end,step],有开始数、终止数、步长;而matlab中是[start:step:end]。
a[:,0],选取第一列
a[0,:],选取第一行
5、numpy中数组赋值时,如果没有超过原始数组维数时,只将引用赋值,而不是复制赋值。
如果想要进行复制,需要使用函数B=A.copy(),与matlab有区别例如:
import numpy as np
b=np.ones((3,3))
c=b;
print 'b\n',b
print 'c:\n',c
c[0,0]=12;
print 'b\n',b
print 'c:\n',c b
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
c:
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
b
[[ 12. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
c:
[[ 12. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
6、 2维矩阵matrix,python中matrix只能是二维的。
简单应用,矩阵乘
a=np.matrix([[1,2,3],[4,5,6],[7,8,9]]);
b=np.matrix([[1],[0],[0]]);
a*b
matrix([[1],
[4],
[7]])
也可以使用数组点积表示:
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
x=np.array([[1],[0],[0]])
A.dot(x)
array([[1],
[4],
[7]])
7、当需要将数组转换成矩阵时,要使用np.matrix(A)
例如
a=np.ones((3,3)); b=np.ones((3,1)); np.matrix(a)*b matrix([[ 3.],
[ 3.],
[ 3.]])
8、深度复制,对于列表、元组、字典想要复制,需要使用copy模块里deepcopy函数
例如:
import copy as cp
a=[[,,],[,,]];
b=cp.deepcopy(a);
a[][]=;
print a
print b
9、array是元素与元素之间的运算
matrices是服从线性代数运算法则
通过dot来更改运算方式
x=np.ones((,));
y=np.ones((,));
print np.dot(x,y) [[ . .]
[ . .]]
array数据类型转换成matrix类型,需要使用Z=asmatrix(A)或Z=mat(A)
a=array([,,]);
a*a
a=np.array([1,2,3]);
a*a
array([1, 4, 9])
10、type、dtype、shape用法
type用来说明数据类型type(A)
dtype是用来指示array数据类型A.dtype
shape用来说明array的大小,A.shape