python - 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 结构?
从我所看到的嵌套类可以完成这项工作。还有其他更有效的方法吗?
解决方案
您可以使用很多选项来使用字典,或者如您所说构建自己的类。如果您从 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()
推荐阅读
- python - Python3汉字转json
- r - 重复循环在R中没有效果
- javascript - myArray.map 不是函数:尝试使用来自 Javascript Fetch API 的数据设置 React 状态
- java - 为什么 API HTTP 响应 406 尽管没有传递接受标头?
- r - 为什么这是我的线性模型的输出,我该如何解决?
- oracle - 如何在 Oracle 中为 1 列创建具有特定值的约束唯一多列?
- swift - 多次调用 SpeechKit 函数结果
- python - 如何在函数中同时使用 (self , request) 参数
- python-3.x - 使用 Python 进行 PDF 文本挖掘
- python - 在python中带有dict的IndexError,