simulink仿真

simulink仿真中需要使用S-Function模块,可以实现调用C程序进行仿真,下面先建立一个简单的仿真;

具体如下图所示;

创建C程序

需要在S-Function模块的S-Function name一栏填写需要调用C程序文件名,注意不需要带文件名后缀;



之后,新建文件sfun_myc.cppsfun_myc.h,放置在simulink仿真的同一级目录下,如下图所示;



sfun_myc.h如下;

/* Copyright 2003-2004 The MathWorks, Inc. */

#ifndef _SFUN_MYC_CPP_
#define _SFUN_MYC_CPP_ // Define a generic template that can accumulate
// values of any numeric data type
template <class DataType> class GenericAdder {
private:
DataType Peak;
public:
GenericAdder() {
Peak = 0;
}
DataType AddTo(DataType Val) {
Peak += Val;
return Peak;
}
DataType GetPeak() const {
return Peak;
}
void SetPeak(DataType v) {
Peak = v;
}
}; // Specialize the generic adder to a 'double'
// data type adder
class DoubleAdder : public GenericAdder<double> {}; #endif

sfun_myc.cpp如下;

/* Copyright 2003-2004 The MathWorks, Inc. */

// *******************************************************************
// **** To build this mex function use: mex sfun_cppcount_cpp.cpp ****
// ******************************************************************* #include "sfun_myc.h" #define S_FUNCTION_LEVEL 2
#define S_FUNCTION_NAME sfun_myc // Need to include simstruc.h for the definition of the SimStruct and
// its associated macro definitions.
#include "simstruc.h" #define IS_PARAM_DOUBLE(pVal) (mxIsNumeric(pVal) && !mxIsLogical(pVal) &&\
!mxIsEmpty(pVal) && !mxIsSparse(pVal) && !mxIsComplex(pVal) && mxIsDouble(pVal)) // Function: mdlInitializeSizes ===============================================
// Abstract:
// The sizes information is used by Simulink to determine the S-function
// block's characteristics (number of inputs, outputs, states, etc.).
static void mdlInitializeSizes(SimStruct *S)
{
// No expected parameters
ssSetNumSFcnParams(S, 0); // Parameter mismatch will be reported by Simulink
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return;
} // Specify I/O
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetInputPortDirectFeedThrough(S, 0, 1);
if (!ssSetNumOutputPorts(S,1)) return;
ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED); ssSetNumSampleTimes(S, 1); // Reserve place for C++ object
ssSetNumPWork(S, 1); ssSetSimStateCompliance(S, USE_CUSTOM_SIM_STATE); ssSetOptions(S,
SS_OPTION_WORKS_WITH_CODE_REUSE |
SS_OPTION_EXCEPTION_FREE_CODE); } // Function: mdlInitializeSampleTimes =========================================
// Abstract:
// This function is used to specify the sample time(s) for your
// S-function. You must register the same number of sample times as
// specified in ssSetNumSampleTimes.
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
ssSetModelReferenceSampleTimeDefaultInheritance(S);
} // Function: mdlStart =======================================================
// Abstract:
// This function is called once at start of model execution. If you
// have states that should be initialized once, this is the place
// to do it.
#define MDL_START
static void mdlStart(SimStruct *S)
{
// Store new C++ object in the pointers vector
DoubleAdder *da = new DoubleAdder();
ssGetPWork(S)[0] = da;
} // Function: mdlOutputs =======================================================
// Abstract:
// In this function, you compute the outputs of your S-function
// block.
static void mdlOutputs(SimStruct *S, int_T tid)
{
// Retrieve C++ object from the pointers vector
DoubleAdder *da = static_cast<DoubleAdder *>(ssGetPWork(S)[0]); // Get data addresses of I/O
InputRealPtrsType u = ssGetInputPortRealSignalPtrs(S,0);
real_T *y = ssGetOutputPortRealSignal(S, 0); // Call AddTo method and return peak value
// y[0] = da->AddTo(*u[0]);
y[0] = *u[0] + 100;
} /* Define to indicate that this S-Function has the mdlG[S]etSimState mothods */
#define MDL_SIM_STATE /* Function: mdlGetSimState =====================================================
* Abstract:
*
*/
static mxArray* mdlGetSimState(SimStruct* S)
{
// Retrieve C++ object from the pointers vector
DoubleAdder *da = static_cast<DoubleAdder*>(ssGetPWork(S)[0]);
return mxCreateDoubleScalar(da->GetPeak());
}
/* Function: mdlGetSimState =====================================================
* Abstract:
*
*/
static void mdlSetSimState(SimStruct* S, const mxArray* ma)
{
// Retrieve C++ object from the pointers vector
DoubleAdder *da = static_cast<DoubleAdder*>(ssGetPWork(S)[0]);
da->SetPeak(mxGetPr(ma)[0]);
} // Function: mdlTerminate =====================================================
// Abstract:
// In this function, you should perform any actions that are necessary
// at the termination of a simulation. For example, if memory was
// allocated in mdlStart, this is the place to free it.
static void mdlTerminate(SimStruct *S)
{
// Retrieve and destroy C++ object
DoubleAdder *da = static_cast<DoubleAdder *>(ssGetPWork(S)[0]);
delete da;
} // Required S-function trailer
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif

最终在static void mdlOutputs(SimStruct *S, int_T tid)函数中对输入的数据进行处理即可;

static void mdlOutputs(SimStruct *S, int_T tid)
{
// Retrieve C++ object from the pointers vector
DoubleAdder *da = static_cast<DoubleAdder *>(ssGetPWork(S)[0]); // Get data addresses of I/O
InputRealPtrsType u = ssGetInputPortRealSignalPtrs(S,0); // 输入
real_T *y = ssGetOutputPortRealSignal(S, 0); // 输出 // Call AddTo method and return peak value
// y[0] = da->AddTo(*u[0]);
y[0] = *u[0] + 100; //增加100的偏移量
}

编译C程序

查看当前路径下是否已经存在C文件,sfun_myc.hsfun_myc.cpp



使用mex指令编译sfun_myc.cpp;

运行结果

最终的运行结果,经过S-Function模块处理的波形比原来的波形偏移了100了,期望结果符合程序的逻辑,具体如下图所示;

链接:百度云下载

提取码:jnmg

matlab 调用C程序进行simulink仿真的更多相关文章

  1. MATLAB调用C程序、调试和LDPC译码

    MATLAB是一个很好用的工具.利用MATLAB脚本进行科学计算也特别方便快捷.但是代码存在较多循环时,MATLAB运行速度极慢.如果不想放弃MATLAB中大量方便使用的库,又希望代码能迅速快捷的运行 ...

  2. Matlab调用C程序

    Matlab调用C程序   复制来自https://blog.csdn.net/u010839382/article/details/42463237 Matlab是矩阵语言,如果运算可以用矩阵实现, ...

  3. Matlab调用C程序 分类: Matlab c/c++ 2015-01-06 19:18 464人阅读 评论(0) 收藏

    Matlab是矩阵语言,如果运算可以用矩阵实现,其运算速度非常快.但若运算中涉及到大量循环,Matlab的速度令人难以忍受的.当必须使用for循环且找不到对应的矩阵运算来等效时,可以将耗时长的函数用C ...

  4. MATLAB设计模糊控制器并用simulink仿真

    一.设计模糊控制器1.1 创建项目文件夹在此路径如图 1.2 打开MATLAB打开MATLAB R2012a切换当前目录为上一步路径,如图 1.3 设计模糊控制器打开模糊控制器设计对话框 根据模糊控制 ...

  5. matlab调用c程序(转载)

    通过把耗时长的函数用c语言实现,并编译成mex函数可以加快执行速度. Matlab本身是不带c语言的编译器的,所以要求你的机器上已经安装有VC,BC或Watcom C中的一种. 如果你在安装Matla ...

  6. 【Matlab】简单的滑模控制程序及Simulink仿真

    文章: [控制理论]滑模控制最强解析 滑模控制程序及Simulink仿真 这篇文章仿真和输出U的推到有些问题,博主根据此篇文章进行修改进行对sin(t)曲线的追踪(使用滑模控制) 使用滑模控制对sin ...

  7. Simulink仿真入门到精通(十) S函数

    10.1 S函数概述 S函数也称为Simulink中的系统函数,是用来描述模块的Simulink宏函数,支持M.C等多种语言.当Simulink默认的模块不能满足用户的需求时,用户可以通过S函数自己打 ...

  8. 基于MATLAB的单级倒立摆仿真

    有关代码及word文档请关注公众号“浮光倾云”,后台回复A010.02即可获取 一.单级倒立摆概述 倒立摆是处于倒置不稳定状态,人为控制使其处于动态平衡的一种摆,是一类典型的快速.多变量.非线性.强耦 ...

  9. Simulink仿真入门到精通(五) Simulink模型的仿真

    5.1 模型的配置仿真 由各种模块所构建的可视化逻辑连接,只是模型的外在表现,模型仿真的核心驱动器是被称作解算器(Solver)的组件,相当于Simulink仿真过程的心脏,驱动着模型仿真,它在每一个 ...

随机推荐

  1. PAS

    一.概念 二.安装 打开Delphi,在主菜单上选择Component,单击Install Component,出现图所示的对话框.有两个选择,装到已经存在的包里面和装到新的包里面.我们选择后者,单击 ...

  2. Git把本地代码推送到远程github仓库

    运用Git版本控制系统进行代码的管理,以便于团队成员的协作,由于之前是使用svn来进行版本控制,所以对于Git使用还有待熟练掌握.Git与svn类似,个人认为两者之间比较直观的区别就是 Git 不需要 ...

  3. 掌握MySQL连接查询到底什么是驱动表

    准备我们需要的表结构和数据 两张表 studnet(学生)表和score(成绩)表, 创建表的SQL语句如下 CREATE TABLE `student` ( `id` int(11) NOT NUL ...

  4. 乱 七 八 糟 $(n.)$

    \(2020/4/22\) 今天常规作业还是太慢了,白天似乎已经抓紧了,但总还能挤出时间来的.八点钟了还有物理和英语作业,回去又得很晚睡. 还是容易开小差,不过回忆了一下,今天化学课还是太懒散,其余的 ...

  5. 树莓派4b 上手三板斧

    树莓派4b 上手三板斧 1.无屏幕和网线连接准备 windows / mac 电脑下载安装Notepad++ 新建文件并保存为ssh(该文件为空文件) 新建文件wpa_supplicant.conf ...

  6. 原生Js贪吃蛇游戏实战开发笔记

    前言 本课程是通过JavaScript结合WebAPI DOM实现的一版网页游戏---贪吃蛇的开发全过程,采用面向以象的思想设计开发.通过这个小游戏的开发, 不仅可以掌握JS的语法的应用,还可以学会D ...

  7. 白话理解https

    为什么需要加密? 因为http的内容是明文传输的,传输过程有可能被劫持或被篡改(中间人攻击),如何解决? 当然是加密.最简单的方式就是对称加密(快). 对称机密 就是一个密钥,可以理解为一把钥匙,我们 ...

  8. JDBC 进阶:使用封装通用DML DQL 和结构分层以及at com.mysql.jdbc.PreparedStatement.setTimestamp空指针异常解决

    准备: 数据表 CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(10) DEFAULT ...

  9. 9个小技巧让你的 if else看起来更优雅

    if else 是我们写代码时,使用频率最高的关键词之一,然而有时过多的 if else 会让我们感到脑壳疼,例如下面这个伪代码: 是不是很奔溃?虽然他是伪代码,并且看起来也很夸张,但在现实中,当我们 ...

  10. redis的5种数据类型

    卸载服务:redis-server --service-uninstall 开启服务:redis-server --service-start 停止服务:redis-server --service- ...