[英]Multiply Matrix by column vector with variable entry that has range (1,101)
I want to multiply Matrix AB. 我想乘以矩阵AB。 To get the vector Y, Where A is 3x4 and B is 4x1 x= range(1,101) B = [2,x,3,x] Since B contains the variable x we will get 100 different vectors for Y. I want to add them to a list so I can use these vectors for computations later on. 要获得向量Y,其中A为3x4,B为4x1 x = range(1,101)B = [2,x,3,x]由于B包含变量x,我们将为Y获得100个不同的向量。我想添加它们列出来,以便以后可以使用这些向量进行计算。
This is what i've tried but i get an error messages 这是我尝试过的但收到错误消息
AB= list()
for x in range (1,100):
A = np.matrix('1 9 2 3; 7 2 1 4; 4 2 5 2')
B = ('2; x; 3; x')
AB.append(A @ B)
What am I doing wrong? 我究竟做错了什么? The error i get is: (that refers to a different file btw) 我得到的错误是:(指的是另一个文件顺便说一句)
raise ValueError('malformed node or string: ' + repr(node))
Okay first, you forgot to make B a numpy matrix, second you need to use f-strings to use x as a variable instead of the character x which is an incompatible type. 好的,首先,您忘记使B成为一个numpy矩阵,其次,您需要使用f字符串将x用作变量,而不是不兼容的字符x。
AB = list()
for x in range (1,100):
A = np.matrix('1 9 2 3; 7 2 1 4; 4 2 5 2')
B = np.matrix(f'2; {x}; 3; {x}')
AB.append(A @ B)
The preferred way of creating arrays is: 创建数组的首选方法是:
In [146]: A = np.array([[1, 9, 2, 3],[7, 2, 1, 4],[4, 2, 5, 2]])
In [147]: A
Out[147]:
array([[1, 9, 2, 3],
[7, 2, 1, 4],
[4, 2, 5, 2]])
For small arrays np.matrix
with its imitation MATLAB constructor is convenient, but generally discouraged. 对于小数组, np.matrix
及其模仿MATLAB构造函数很方便,但通常不建议这样做。
In [148]: x=3
In [149]: B = np.array([[2],[x],[3],[x]])
In [150]: B
Out[150]:
array([[2],
[3],
[3],
[3]])
# B = np.array([[2,x,3,x]]).T
In [151]: A@B
Out[151]:
array([[44],
[35],
[35]])
For multiple values of x
: 对于x
多个值:
In [152]: x = np.arange(10)
In [153]: B = np.empty((4,x.shape[0]), int)
In [154]: B[[1,3]] = x
In [155]: B[0] = 2
In [156]: B[2] = 3
In [157]: B
Out[157]:
array([[2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
In [158]: A@B
Out[158]:
array([[ 8, 20, 32, 44, 56, 68, 80, 92, 104, 116],
[ 17, 23, 29, 35, 41, 47, 53, 59, 65, 71],
[ 23, 27, 31, 35, 39, 43, 47, 51, 55, 59]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.