[英]How to assign variables to numpy matrix
I want to make a function to generate rotational matrix R. Here is my code: 我想制作一个函数来生成旋转矩阵R。这是我的代码:
import numpy as np
def R(theta):
a = np.cos(theta)
b = -1*np.sin(theta)
c = np.sin(theta)
d = np.cos(theta)
return np.matrix('a b; c d')
But it has error like this 但是它有这样的错误
raise TypeError("Invalid data string supplied: " + astr)
TypeError: Invalid data string supplied: a
Any suggestions? 有什么建议么?
使用.format将变量放入字符串形式
return np.matrix('{} {};{} {}'.format(a,b,c,d))
That matrix notation: 该矩阵符号:
a = np.matrix('1 2; 3 4')
only works for literals, not variables; 仅适用于文字,不适用于变量; with scalar variables you'd use the bracket notation 与标量变量一起使用括号表示法
np.matrix([[1, 2], [3, 4]])
np.matrix([[a, b], [c, d]])
This part, [[a, b], [c, d]]
is an ordinary Python list (of lists). 这部分[[a, b], [c, d]]
是一个普通的Python列表(列表)。 np.matrix(...)
then takes this list and turns it into a numpy
matrix. 然后, np.matrix(...)
将此列表转换为一个numpy
矩阵。
But really, you should be using 但实际上,您应该使用
np.array(...)
np.matrix
was written to make things familiar to MATLAB visitors. 编写np.matrix
是为了使MATLAB访问者熟悉它们。 Most numpy
work is the array
, not matrix
. 大多数numpy
工作是array
,而不是matrix
。
Another point - a = np.cos(theta)
works with theta
is scalar or an array. 另一点a = np.cos(theta)
与theta
是标量或数组。 But if an array, than a
itself will be an array, not a scalar. 但是,如果是数组, a
本身就是数组,而不是标量。 You should be aware of that when constructing this rotation matrix. 在构造此旋转矩阵时,您应该意识到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.