分享

Python vs Matlab性能比拼 — 求逆矩阵

 基算仿真 2023-05-30 发布于江苏

这次比较一下Python(Numpy)与Matlab关于矩阵求逆问题速度的对比。

测试项目为:

  • 生成一个1000x1000的随机矩阵。

  • 判断其行列式是否为0(逆矩阵存在条件)。

  • 若矩阵的行列式不为0则求解其逆矩阵。

  • 重复100次计算并求出平均用时。

01

Python

在Python上依旧使用了Numpy进行矩阵运算。

import numpy as npfrom time import timefrom numpy.linalg import inv
n = int(1e3)trials = int(1e2)run_time = []
for i in range(trials): A = np.random.randint(1, 100, (n, n)) while(np.linalg.det(A) == 0): A = np.random.randint(1, 100, (n, n))
t1 = time() inv_A = inv(A) run_time.append(time() - t1) print(f"{i+1} runs complete")
print(f"平均用时: {np.mean(run_time)}")

计算结果为:

02

Matlab

Matlab代码如下:

clc; clear; close all;
n = 1e3;trials = 1e2;time = zeros(trials, 1);
for i = 1:trials A = ceil(100*rand(n, n)); % must be invertable while(det(A) == 0) A = ceil(100*rand(n, n)); end tic A_inv = inv(A); time(i) = toc; fprintf('%d runs complete\n', i)end
fprintf('平均用时: %f seconds\n', mean(time))

计算结果为:

通过对比可以发现在求解逆矩阵问题方面,Matlab的计算效率更高一些。

以上测试结果受计算机配置及软件版本的影响可能会有所不同,大家感兴趣的话可以在自己的计算机上尝试一下。

—— end ——

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多