Python Matlab engine - Cannot read simulink output

조회 수: 35 (최근 30일)
Pier-Yves Lessard
Pier-Yves Lessard 2021년 12월 6일
편집: Pier-Yves Lessard 2021년 12월 6일
I'm trying to read the output of a Simulink simulation through Python with Matlab Engine but I'm having trouble as I am not able to get the output data.
But it doesn't work for me.
calling sim() does not add the output to the workspace and the object it returns has no usable properties (except size)
Python 3.6.4. Matlab 2020b
Thank you
import matlab
import matlab.engine as matlabEngine
import math
import numpy as np
import time
class LogTime:
def __init__(self, action):
self.action = action
def __enter__(self):
print('%s...' % self.action, end='', flush=True)
self.time_start = time.time()
def __exit__(self, *args, **kwargs):
print('Done in %0.3f seconds' % (time.time()-self.time_start))
# Params
modelname = 'simpleModel'
stopTime = 1;
nbPoints = 10000;
simstep = 0.0001;
with LogTime('Starting Matlab Engine'):
m = matlabEngine.start_matlab();
t = np.linspace(0,stopTime,nbPoints)
voltage = 120*math.sqrt(2)*np.sin(2*math.pi*60*t)
current = 120*math.sqrt(2)*np.sin(2*math.pi*60*t + math.pi/8)
# Numpy to matlab conversion
t = matlab.double(t.tolist())
voltage = matlab.double(voltage.tolist())
current = matlab.double(current.tolist())
# Write to workspace for model
m.workspace['input_voltage'] = m.timeseries(voltage, t)
m.workspace['input_current'] = m.timeseries(current, t)
with LogTime('Loading Model'):
m.load_system(modelname, nargout=0)
m.set_param(modelname, 'StopTime', str(stopTime), 'FixedStep', str(simstep), nargout=0)
with LogTime('Running simulation'):
out = m.sim(modelname) # Empty object. don't know what to do with it.

채택된 답변

Pier-Yves Lessard
Pier-Yves Lessard 2021년 12월 6일
편집: Pier-Yves Lessard 2021년 12월 6일
I finally made it work.
the object return by sim() is a SimulationOutput object and it can be access by calling its method and passing the object as first parameter.
m.get(out, '<signalName>')
This worked
ts = m.get(out, 'power')
out_data = m.transpose(m.get(ts, 'Data')[0])
out_time = m.get(ts, 'Time')
t2 = np.array(out_time)
power = np.array(out_data)
from matplotlib import pyplot as plt
plt.plot(t2, power)
plt.show()
input('Press any key...')

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2021년 12월 6일
Extract the simout to a timetable, then pass the timetable back to python either via writing to disk as a CSV, or converting to a struct (timetable2table(table2struct()) directly back to python.

카테고리

Help CenterFile Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by