【发布时间】:2018-07-20 19:27:05
【问题描述】:
我想知道是否有人可以帮助我理解 C 语言中 Matlab 引擎的语法。我是 C 语言的初学者,正在尝试使用 Matlab 引擎在 C 语言中调用自定义 Matlab 函数。我所做的研究包括阅读 Matlab API 的文档、观看 Mathworks 的讲座视频、研究 Stack Overflow、阅读 Matlab 中的示例 eng.c 文件和 Google。
我想出了这段代码,它可以编译但输出返回零。输入数组也不返回数组,而是返回一个 int。我找不到关于如何构建 C 脚本的全面演练视频
- 接受一个向量
- 将其输入 Matlab 函数并
- 返回输出。
文档非常清楚地解释了创建数组,但我找不到详细说明将数组读取到 Matlab 中然后获取输出的信息。
下面,请查看包含 cmets 的代码,了解我理解的每个代码部分的作用。示例函数add_up 只是在数组上调用sum 函数。任何帮助都会很棒,因为我不知道为什么返回零。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define BUFSIZE 256
int main() {
//Open call to matlab engine
Engine *ep;
//Use this conjunction with define BUFSIZe 256 to create double
//extData is a variable to read external data
//Number in brackets refer to size
//We are using double in this case and create the external data using initialization
double extData[10]={1.0,4.0,7.0,2.0,5.0,8.0,3.0,6.0,9.0,10.0};
//Next step is to make a pointer of type mxArray
//These are pointers to an array of any size or type
mxArray *pVarNum;
double *outp;
//After we make a matrix for the double data initialized above
//Initialized to 0
pVarNum=mxCreateDoubleMatrix(1,10,mxREAL);
//Our array needs to be assigned a variable name for Matlab
//Workspace
//const char *myDouble = "T";
//Our matlab matrix is initialized to zero. We need to use
//The C memcpy function to get the data from extData to
//Get the array data using the pointer to pVarNum
//Use mxGetPr, a mxGet function
memcpy((void *)(mxGetPr(pVarNum)), (void *)extData,sizeof(extData));
//Place the variable T into the Matlab workspace
engPutVariable(ep,"T",pVarNum);
//Evalute test function
engEvalString(ep, "out=T+1");
//Make a pointer to the matlab variable
outp=engGetVariable(ep,"out");
//Now make a pointer to the C variable
printf("%d\n",outp);
printf("Done!\n");
mxDestroyArray(pVarNum);
engClose(ep);
return EXIT_SUCCESS;
}
【问题讨论】:
标签: c matlab matlab-engine