栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实现从键盘输入两个矩阵并相乘

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实现从键盘输入两个矩阵并相乘

不使用numpy自带的np.dot()实现从键盘输入两个矩阵并相乘

代码

import numpy as np

def matrix_multiplication(matrix_1, matrix_2):
    h1,w1 = matrix_1.shape
    h2,w2 = matrix_2.shape
    answer = []
    temp_answer = 0
    assert w1 == h2, "shape mismatching, check the shape of two input matrix"

    for i in range(h1):
        for k in range(w2):
            for j in range(w1):
                temp_answer = temp_answer + matrix_1[i][j] * matrix_2[j][k]
            answer.append(temp_answer)
            temp_answer = 0
    answer = np.reshape(answer, (h1, w2))
    return answer


# 从键盘输入两个矩阵的形状以及它们对应的值
matrix_1_shape = input("Input matrix_1's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix":)
matrix_1 = input("Input matrix_1's value, use ',' to separate,such'1,2,3' for the (1,3) shape matrix":)
matrix_2_shape = input("Input matrix_2's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:")
matrix_2 = input("Input matrix_2, use ',' to separate, such'1,2,3' for the (1,3) shape matrix:")
matrix_1_shape = [int(x) for x in matrix_1_shape.split(',')]
matrix_2_shape = [int(x) for x in matrix_2_shape.split(',')]
matrix_1 = np.array([int(x) for x in matrix_1.split(',')])
matrix_2 = np.array([int(x) for x in matrix_2.split(',')])
matrix_1 = np.reshape(matrix_1,(matrix_1_shape[0],matrix_1_shape[1]))
matrix_2 = np.reshape(matrix_2,(matrix_2_shape[0],matrix_2_shape[1]))

print(matrix_1.shape,matrix_2.shape)

c = matrix_multiplication(matrix_1, matrix_2)
print(c.shape)
d = np.dot(matrix_1, matrix_2)  # 与numpy自带的矩阵相乘函数结果进行对比
print(d.shape)
assert (c == d).all(), "logic error, check your code"
print('well done')

运行结果:

Input matrix_1's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:1,2
Input matrix_1's value, use ',' to separate,such'1,2,3' for the (1,3) shape matrix:1,2
Input matrix_2's shape, use ',' to separate, eg:1,3 means the (1,3) shape matrix:2,1
Input matrix_2, use ',' to separate, such'1,2,3' for the (1,3) shape matrix:1,2
(1, 2) (2, 1)
(1, 1)
(1, 1)
well done
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号