【发布时间】:2019-05-12 16:22:50
【问题描述】:
我必须实现一些将矩阵设置为单位矩阵的方法。听起来很简单,但我不能使用 NumPy。
class Matrix4():
def __init__(self, row1=None, row2=None, row3=None, row4=None):
"""Constructor for Matrix4
DO NOT MODIFY THIS METHOD"""
if row1 is None: row1 = Vec4()
if row2 is None: row2 = Vec4()
if row3 is None: row3 = Vec4()
if row4 is None: row4 = Vec4()
self.m_values = [row1,row2,row3,row4]
def __str__(self):
"""Returns a string representation of the matrix
DO NOT MODIFY THIS METHOD"""
toReturn = ''
if self is None: return '0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00'
for r in range(0,4):
for c in range(0,4):
toReturn += "%.2f" % self.m_values[r].values[c]
if c != 3:
toReturn += ' '
toReturn += '\n'
return toReturn
def setIdentity(self):
"""Sets the current Matrix to an identity matrix
self is an identity matrix after calling this method"""
row1 = Vec4(1,0,0,0)
row2 = Vec4(0,1,0,0)
row3 = Vec4(0,0,1,0)
row4 = Vec4(0,0,0,1)
setIdentity.Matrix4()
return Matrix4(row1, row2, row3, row4)
如您所见,我们有一个 Matrix4() 类,到目前为止我已经实现了该方法。如果我尝试打印出单位矩阵,它会失败。 命令
print(Matrix4())
打印出零矩阵。执行以下命令
print(setIdentity.Matrix4())
告诉我 setIdentity 没有实现。我的代码有什么问题?
我愿意接受您的建议。
谢谢!
【问题讨论】:
-
Vec4() 是做什么的?
-
你需要做的,
Matrix4().setIdentity() -
这对我不起作用,马特。它说 setIdentity 没有定义。
-
你可以改变什么方法?您必须从您的方法
setIdentity.Matrix4()中删除该行是乱码和损坏的。 -
谢谢,这就是问题所在。现在它工作正常。
标签: python-3.x matrix-multiplication vector-multiplication