【问题标题】:List of matrices: plot each element of matrix as a function of an index矩阵列表:将矩阵的每个元素绘制为索引的函数
【发布时间】:2021-04-20 10:55:16
【问题描述】:

我有一个矩阵列表。我想在另一个列表的函数中绘制这些矩阵的每个元素。

但是我在不使用循环的情况下努力做到这一点。

我怎样才能以最简单的方式做到这一点?

下面的代码解释了我想要做什么。

import numpy as np
from numpy import *
from matplotlib.pyplot import *
import matplotlib.pyplot as plt
from mpmath import *
import mpmath as mpmath
import pylab
import numpy
import time 
import math
from qutip.sparse import sp_eigs
import numpy, scipy.io
from random import *

randomMatrixList=[np.random.rand(2,2) for _ in range(10)]
index=np.arange(10)

# I want to plot on x axis: index, on y axis: randomMatrixList[ii][0] for ii
# corresponding to index[ii] for the "0" curve, then randomMatrixList[ii][1] for the first one, and so on

【问题讨论】:

  • 请删除所有不必要的代码。大多数导入都不需要(例如timepylab 等)。

标签: python list numpy matplotlib


【解决方案1】:

我认为没有任何方法可以完全不使用循环,但这种方法有点紧凑。如果您愿意,还可以做一些更聪明的事情,但下面的代码在明确性和易于理解方面进行了权衡。

import numpy as np
import matplotlib.pyplot as plt

randomMatrixList = [np.random.rand(2, 2) for _ in range(10)]
index = np.arange(10)

stacked_matrices = np.array(randomMatrixList)
print(stacked_matrices.shape)
for k in range(stacked_matrices.shape[1]):
    for j in range(stacked_matrices.shape[2]):
        plt.plot(index, stacked_matrices[:, j, k], label=f"mat[{j},{k}]")

plt.legend()
plt.xlabel("index")
plt.show()

代码生成下面的图像

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2017-02-10
    • 2011-11-15
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多