首页 > 解决方案 > python中MATLAB结构的替代方案

问题描述

我在 MATLAB 中有一个结构,如下所示:

model(1:2).energy(1:3).voltage(1:4).time(1:10000)  
model(1:2).energy(1:3).voltage(1:4).current(1:10000)

我正在做的基本操作是绘制电流与时间的关系图。

我想开始使用python,但我对它不是很熟悉。我可以使用哪种具有类似功能的 python 结构?

从我所看到的嵌套类可以完成这项工作。还有其他更有效的方法吗?

标签: pythonmatlabfile-iodata-analysis

解决方案


您可以使用很多选项来使用字典,或者如您所说构建自己的类。如果您从 matlab 迁移,还可以考虑 numpy 模块,因为它使操作数组(或矩阵)变得轻而易举。以下是如何使用它们的简短示例。

import numpy as np
import matplotlib.pyplot as plt

time = np.linspace(0.0, 10.0, 51)
current = np.random.randint(115,125,size=(51))
voltage =  current*(time**2)


#Dictionary Example
model_dict = {'time': time, 'voltage': voltage, 'current': current}
plt_attr = {'color': ['r','b','g','k']}

fig, ax1 = plt.subplots(2,1)
ax1[0].title.set_text('Dictionary Example')
ax1[0].set_xlabel('time (s)')
ax1[0].set_ylabel('Voltage [V]', color=plt_attr['color'][0])
# Note how the variables are called
ax1[0].plot(model_dict['time'], model_dict['voltage'], color=plt_attr['color'][0])
ax1[0].tick_params(axis='y', labelcolor=plt_attr['color'][0])
ax2 = ax1[0].twinx()  # instantiate a second axes that shares the same x-axis

ax2.set_ylabel('Current [Amp]', color=plt_attr['color'][1])  # we already handled the x-label with ax1
# Note how the variables are called
ax2.plot(model_dict['time'], model_dict['current'], color=plt_attr['color'][1])
ax2.tick_params(axis='y', labelcolor=plt_attr['color'][1])

#Class Example
class model:
    def __init__(self, name, i = None, v = None, e = None, t = None):
        self.name = name
        self.current = i
        self.voltage = v
        self.energy = e
        self.time = t

model_class = model('model_1', i = current, v = voltage, t = time)   

ax1[1].title.set_text('Class Example')
ax1[1].set_xlabel('time (s)')
ax1[1].set_ylabel('Voltage [V]', color=plt_attr['color'][2])
# Note how the variables are called
ax1[1].plot(model_class.time, model_class.voltage, color=plt_attr['color'][2])
ax1[1].tick_params(axis='y', labelcolor=plt_attr['color'][2])

ax2 = ax1[1].twinx()  # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('Current [Amp]', color=plt_attr['color'][3])  # we already handled the x-label with ax1
# Note how the variables are called
ax2.plot(model_class.time, model_class.current, color=plt_attr['color'][3])
ax2.tick_params(axis='y', labelcolor=plt_attr['color'][3])
plt.show()

推荐阅读