矩阵列表:将矩阵的每个元素绘制为索引的函数

时间:2021-01-15 11:53:13

标签: python list numpy matplotlib

我有一个矩阵列表。我想根据另一个列表绘制这些矩阵的每个元素。

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

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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()

代码产生下面的图像 plot of the indices of the matrices