⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 engdemo.c

📁 在VC中对MATLAB进行调用的例子。简单地进行了一些设置说明
💻 C
字号:
/*	engdemo.c
 *
 *  这个简单的例子说明了如何从C程序中调用MATLAB的函数.   ZLF
 *
 * Copyright 1984-2000 The MathWorks, Inc.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"  //加载外部头文件,为MATLAB的头文件.  位于MATLAB\...\include\ 下。
#define  BUFSIZE 256

int main()

{
	mxArray *T = NULL, *result=NULL;
	Engine *ep;
	//Engine *ep=NULL;+++
	char buffer[BUFSIZE];
	double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };
    char zlf;


	/*
	 * 通过执行字符串"matlab"在本地启动MATLAB工程
	 *
	 * 要启动远程机器上的MATLAB工程,(下面的参数字符串) 使用主机名名字,不使用"\0"
	 *
	 * 对于更多较为复杂的情况,可以使用带空格的字符串,该字符串能够被逐字的解释
	 * 来启动MATLAB
	 */

	if (!(ep = engOpen("\0"))) {  //打开Matlab工程,而且只打开其COMMAND窗口
		fprintf(stderr, "\nCan't start MATLAB engine\n");
		return EXIT_FAILURE;  //EXIT_FAILURE : STDLIB.H 中的常量
	}

	/* 
	 * PART I
	 * 
	 * For the first half of this demonstration, we will send data
	 * to MATLAB, analyze the data, and plot the result.
	 */

	T = mxCreateDoubleMatrix(1, 10, mxREAL);
	mxSetName(T, "T");
	memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));  

	engPutArray(ep, T);//将数值拷贝到MATLAB workspace中,同时在MATLAB中生成数组T

	engEvalString(ep, "D = .5.*(-9.8).*T.^2;");

	engEvalString(ep, "plot(T,D);");
	engEvalString(ep, "title('Position vs. Time for a falling object');");
	engEvalString(ep, "xlabel('Time (seconds)');");
	engEvalString(ep, "ylabel('Position (meters)');");

	printf("Hit return to continue\n\n");
	fgetc(stdin);

	/*
	 * We're done for Part I! Free memory, close MATLAB engine(引擎/工程???).
	 */
	printf("Done for Part I.\n");
	//mxDestroyArray(T);  //此命令不起作用,应使用   ZLF
	engEvalString(ep, "clear T");
	engEvalString(ep, "close;");


	// PART II
	engOutputBuffer(ep, buffer, BUFSIZE);  //用buffer来捕捉 Matlab的输出

	while (result == NULL) {
	    char str[BUFSIZE];

	    printf("Enter a MATLAB command to evaluate.  This command should\n");
	    printf("create a variable X.  This program will then determine\n");
	    printf("what kind of variable you created.\n");
	    printf("For example: X = 1:5\n");
	    printf(">> ");
        
		//此处要求变量的名字必须为大写的X,即格式为 X=...
	    fgets(str, BUFSIZE-1, stdin);
	    if (str[0]=='Q') 	{
			break;
		}

	    engEvalString(ep, str);
	    
	    printf("%s", buffer+2);//在C中输出matlab的输出,忽略开头两个引导字符">>"
	    
	    printf("\nRetrieving X...\n");
	    if ((result = engGetArray(ep,"X")) == NULL)  //"X"为变量名  ZLF  030625
	      printf("Oops! You didn't create a variable X.\n\n");
	    else {
		printf("X is class %s\t\n", mxGetClassName(result));
	    }
	}

	/*
	 * We're done! Free memory, close MATLAB engine and exit.
	 */
	printf("Done!\n");
	mxDestroyArray(result);
	//engClose(ep);  //关闭Matlab工程
	


	printf("Please input any key to exit...\n");
    _getch();
	return EXIT_SUCCESS;
}







⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -