在算法开发流程中,主要经过以下几个阶段:
- 算法初始阶段
- 算法仿真阶段
- 算法实现阶段
- 算法移植阶段
在使用MATLAB搭建算法模型仿真得到想要的结果后,就要进行算法实现了,如果要在嵌入式平台实现算法功能,通常要用C代码来实现,比如实现智能穿戴设备上的健康检测算法。本文通过MATLAB调试C代码来验证算法实现阶段的正确性。
MATLAB联调C代码
- 新建一个文件夹,在同一个文件夹里编写所需要实现的算法文件a.m文件、b.c文件、b.h文件
比如在下图中,编写ACCTestAlgm.m文件,MotionDetection.c,MotionDetection.h文件
在编写.m文件时,调用.c文件的格式是 rposbuf = MotionDetection(int32(alginvars));alginvars作为c文件的输入,rposbuf 作为c文件的输出
- 在b.c文件末尾里添加如下代码
AlgTestprocess()函数根据自己的代码来编写,pInVars、pOutVars为算法的输入变量和输出变量 mexFunctiom()根据下面给的参考来编写
#define ALG_DEBUG_FLG 1
#ifdef ALG_DEBUG_FLG
#include "mex.h"
#include "matrix.h"
#endif
#ifdef ALG_DEBUG_FLG
#define LEN_OUT 4
void AlgTestprocess(int* pInVars, int* pOutVars)
{
int init;
ACCINVars InMsg;
ACCOUTVars OutMsg;
//算法输入参数,对应于主调用函数的输入变量
InMsg.accX=pInVars[0];
InMsg.accY=pInVars[1];
InMsg.accZ=pInVars[2];
init=pInVars[3];
//执行算法
if(1==init)
{
GACCInitGlobalVars();
}
else
{
GetACCStateMainFun(&InMsg, &OutMsg);
}
//算法输出结果,对应于调用主函数的输出变量
pOutVars[0] = OutMsg.accX;
pOutVars[1] = OutMsg.accY;
pOutVars[2] = OutMsg.accZ;
pOutVars[3] = OutMsg.state;
}
//mexFunction()函数不需要修改,只需要修改倒数第一、二行
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int* pInDataBuf = NULL;
int* pOutDataBuf = NULL;
if (nrhs != 1) mexErrMsgTxt("four inputs required");
pInDataBuf = (int*)mxGetData(prhs[0]);
if (nlhs != 1) mexErrMsgTxt("one outputs required");
plhs[0] = mxCreateNumericMatrix(1, LEN_OUT, mxINT32_CLASS, mxREAL);
pOutDataBuf = (int*)mxGetData(plhs[0]); //如果算法输出有多个参数变量的话,此处使用指针(int*);如果算法输出有一个参数变量的话,此处使用不加(int*)
AlgTestprocess(pInDataBuf, pOutDataBuf);
}
#endif
-
在MATLAB里输入命令 mex b.c
会生成 b.mexw64 文件 -
在MATALB里输入命令 mex -g b.c
b.mexw64.pdb -
在VS中添加断点,并在工具栏 debug ,attach to process , 选择MATLAB进程即可
-
点击MATLAB运行即可。