bus在matlab里哪里,Matlab中使用脚本和xml文件自动生成bus模块

帮一个老师写的小工具

在一个大工程中需要很多bus来组织信号,而为了规范接口,需要定义很多BusObject,用Matlab语言手写这些BusObject比较费工夫

所以用xml配置文件来写,也便于更改总线数据接口,然后使用matlab脚本来生成BusObject和Bus模块库

以下代码运行环境:WIN10+Matlab2015a

下面给出代码Matlab函数的代码:

function xmlbuscreator(xmlfile)

% XMLBUSCREATOR:从xml文件读取数据结构,并生成bus

% xmlbuscreator(xmlfile):从xmlfile文件读取bus定义,并生成总线

%% 读取文件并提取信号

try

xdoc = xmlread(xmlfile);

catch

error(‘读取XML文件:%s失败.‘,xmlfile);

end

BusLibElement = xdoc.getElementsByTagName(‘BusLib‘);

BusLibItem = BusLibElement.item(0);

BusLibName = BusLibItem.getAttribute(‘Name‘);

BusObjList = BusLibItem.getElementsByTagName(‘BusObject‘);

BusObjNum = BusObjList.getLength;

BusInfo = cell(BusObjNum,1);

for i = 1:BusObjNum

BusObj = BusObjList.item(i-1);

BusName = char(BusObj.getAttribute(‘Name‘));

BusElementsList = BusObj.getElementsByTagName(‘BusElement‘);

ElementNum = BusElementsList.getLength;

% 如何分配一个结构体数组,BusElements = struct();

for j = 1:ElementNum

ele = BusElementsList.item(j-1);

BusElements(j) = Simulink.BusElement;

try

BusElements(j).Name = char(ele.getAttribute(‘Name‘));

BusElements(j).DataType = char(ele.getAttribute(‘DataType‘));

BusElements(j).Dimensions = str2double(ele.getAttribute(‘Dimensions‘));

BusElements(j).SampleTime = -1;

BusElements(j).Complexity = ‘real‘;

BusElements(j).SamplingMode = ‘Sample based‘;

catch me

error(me.message);

end

end

BusObject = Simulink.Bus;

BusObject.HeaderFile = ‘‘;%默认无头文件

BusObject.Description = ‘‘;

BusObject.DataScope = ‘Auto‘;

BusObject.Alignment = -1;

BusObject.Elements = BusElements;

assignin(‘base‘,BusName,BusObject);

BusInfo{i}.BusName = BusName;

BusInfo{i}.Inputs = ElementNum;

end

%% 生成Bus模块

if verLessThan(‘simulink‘,‘8.1‘)%2013a之前用mdl,之后用slx

mdlExt = ‘.mdl‘;

else

mdlExt = ‘.slx‘;

end

BusLibFile = char(BusLibName);

if exist([BusLibFile,mdlExt])

delete([BusLibFile,mdlExt]);%删除原先存在的模型

end

close_system(BusLibFile,0);

new_system(BusLibFile,‘Library‘);

load_system(BusLibFile);

for i = 1:BusObjNum

busblock = add_block(‘built-in/BusCreator‘,[BusLibFile,‘/‘,BusInfo{i}.BusName],‘Position‘,[15+(i-1)*115,19,65+(i-1)*115,121]);

set_param(busblock,‘OutDataTypeStr‘,[‘Bus:‘,BusInfo{i}.BusName]);

set_param(busblock,‘Inputs‘,num2str(BusInfo{i}.Inputs));

end

save_system(BusLibFile);

open_system(BusLibFile);

下面是给出来配置Bus的xml代码:xmlbus.xml

1

2

3

4

5

6

7

8

9

10

11

12

以前没咋用过xml,估计写的有很多该规范的地方,欢迎大家指正。

下面是主代码:

xmlfile = ‘xmlbus.xml‘;

xmlbuscreator(xmlfile);

运行上面代码,则可以生成BusLib3.slx文件,里面包含两个Bus如下图所示:

bus在matlab里哪里,Matlab中使用脚本和xml文件自动生成bus模块_第1张图片

可以看出,生成的两个Bus符合预设的条件,完工。

第一篇记录编程的博客,比较粗糙,发现问题的哥们尽管喷

原文:http://www.cnblogs.com/spyplus/p/5388983.html

你可能感兴趣的:(bus在matlab里哪里)