Simulink如何从工作区导入1×n结构体至MATLAB Function模块?
我在基础工作区定义了结构体input,为避免大量重构,想通过From Workspace模块将其导入Simulink,并在MATLAB Function模块中使用。按资料要求需指定总线对象,但两次尝试均失败:
尝试1:手动创建总线对象与结构体
编写代码创建总线对象和结构体:
elm(1) = Simulink.BusElement; elm(2) = Simulink.BusElement; elm(1).Name = 'a'; elm(2).Name = 'b'; busObj = Simulink.Bus; busObj.Elements = elm; input.a = 1.0; input.b = 2.0;
设置From Workspace模块的Data: input、Output Data Type: Bus: busObj后,报错:
Invalid structure-format variable specified as workspace input in 'test/From Workspace'. If the input signal is a bus signal, the variable must be a structure of MATLAB timeseries objects. Otherwise, the variable must include 'time' and 'signals' fields, and the 'signals' field must be a structure with a 'values' field.
尝试2:用Simulink.SimulationData.createStructOfTimeseries创建时序结构体
执行命令Simulink.SimulationData.createStructOfTimeseries('busObj')时,MATLAB报错:
To construct a MATLAB structure from a bus object, the first argument must be the name of a bus object. The optional second argument can be either a cell array of MATLAB timeseries objects, or a structure of timeseries objects.
备注
input是仅含静态参数的结构体,无需视为时序,能否通过单时间戳外推为常量实现?- 优先希望导入多维结构体(如
1x5 struct with fields: 'a', 'b', ...),单维度也可接受。
解决方案
静态常量结构体的导入方法
因为你的input是静态参数,不需要时序,只需将结构体转换为带单时间戳的时序结构体,即可满足From Workspace的总线输入要求:
明确总线对象定义(建议指定数据类型,避免类型不匹配):
% 定义总线元素并指定类型 elm(1) = Simulink.BusElement('Name','a','DataType','double'); elm(2) = Simulink.BusElement('Name','b','DataType','double'); busObj = Simulink.Bus('Elements',elm); % 将总线对象存入基础工作区 assignin('base','busObj',busObj);转换静态结构体为时序结构体:
给每个字段创建单时间点的timeseries对象,并设置外推方式为常量,确保仿真全程保持静态值:% 初始化静态结构体 input.a = 1.0; input.b = 2.0; % 转换为符合要求的时序结构体 bus_ts = struct; for field = fieldnames(input)' field_name = field{1}; % 创建时间戳为0的timeseries,设置常量外推 bus_ts.(field_name) = timeseries(input.(field_name), 0); bus_ts.(field_name).ExtrapolationMethod = 'constant'; end配置From Workspace模块:
- 设置
Data为bus_ts - 设置
Output Data Type为Bus: busObj - 确认模块的Sample Time设为
-1(继承采样时间)或匹配你的仿真步长
- 设置
多维结构体数组的导入处理
如果是1x5的结构体数组(每个元素含a、b字段),需转换为总线数组的时序结构体:
转换代码示例:
% 示例1x5结构体数组 input_array(1).a = 1; input_array(1).b = 2; input_array(2).a = 3; input_array(2).b = 4; input_array(3).a = 5; input_array(3).b = 6; input_array(4).a = 7; input_array(4).b = 8; input_array(5).a = 9; input_array(5).b = 10; % 转换为总线数组的时序结构体 bus_ts_array = struct; for field = fieldnames(input_array(1))' field_name = field{1}; % 提取数组中该字段的所有值,转为列向量后创建timeseries values = [input_array.(field_name)]'; bus_ts_array.(field_name) = timeseries(values, 0); bus_ts_array.(field_name).ExtrapolationMethod = 'constant'; end模块配置:
在From Workspace模块的Output Data Type选择Bus: busObj后,勾选Array of buses选项即可。
在MATLAB Function模块中使用
导入总线后,在MATLAB Function模块里:
- 右键模块→Edit Data,将输入端口的数据类型设置为
Bus: busObj(如果是总线数组,需勾选Array) - 直接通过字段访问数据,例如:
function y = fcn(input_bus) y = input_bus.a + input_bus.b; end
内容的提问来源于stack exchange,提问作者Maverick

