无需NumPy实现Python矩阵与向量相乘及代码无响应问题排查
无NumPy实现矩阵与向量相乘的代码问题
想要不使用NumPy实现矩阵与向量相乘,先创建非NumPy的向量,但在Jupyter Notebook中运行以下代码时既不报错也无输出:
def multiply(v, G): result = [] for i in range(len(G[0])): #this loops through columns of the matrix total = 0 for j in range(len(v)): #this loops through vector coordinates & rows of matrix total += v[j] * G[j][i] result.append(total) return result
问题原因及解决方法
- 缩进错误:函数内的
result = []语句没有缩进,这属于语法错误。Python要求函数体内部的代码必须缩进(通常为4个空格),否则解释器无法识别它属于函数的一部分。 - 未调用函数:即使修复了缩进,仅定义函数不会产生任何输出,你需要创建测试用的向量和矩阵,调用
multiply函数并打印结果。
修复后的完整代码示例
def multiply(v, G): result = [] # 遍历矩阵的列 for i in range(len(G[0])): total = 0 # 遍历向量元素和矩阵的行 for j in range(len(v)): total += v[j] * G[j][i] result.append(total) return result # 测试用例 vector = [1, 2, 3] matrix = [ [4, 5, 6], [7, 8, 9], [10, 11, 12] ] # 调用函数并打印结果 print(multiply(vector, matrix))
运行这段修复后的代码,就能得到矩阵与向量相乘的结果。
内容的提问来源于stack exchange,提问作者VangKont
相关产品推荐
相关产品推荐

