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

📄 engdemo.c

📁 matlab实用教程
💻 C
字号:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define  BUFSIZE 256
 
int main()
{
    Engine *ep;
    mxArray *T = NULL, *result = NULL;
    char buffer[BUFSIZE+1];
    double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };

    /*  调用engOpen语句启动MATLAB引擎 */
    if (!(ep = engOpen("\0"))) {
        fprintf(stderr, "\nCan't start MATLAB engine\n");
        return EXIT_FAILURE;
    }
 
    /*  PART I  这部分为MATLAB接收程序传来的数据,然后对其分析最后绘图 */
 
    /* 创建临时变量 */
    T = mxCreateDoubleMatrix(1, 10, mxREAL);
    memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
    
    /* 变量T放到MATLAB工作空间  */
    engPutVariable(ep, "T", T);
 
    /* 计算distance = (1/2)g.*t.^2的值,g为重力加速度,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)');");
 
    /* fgetc()确保结果图像停留时间足够长,如果太短则“看”不到图像  */
    printf("Hit return to continue\n\n");
    fgetc(stdin);

    /* 第一部分完毕,释放内存,关闭MATLAB引擎 */
    printf("Done for Part I.\n");
    mxDestroyArray(T);
    engEvalString(ep, "close;");

    /*  PART II  这部分要求用户输入一个字符串,MATLAB执行这个字符串,
     * 然后创建变量X,并识别X的数据类型  */
      
    /* 使用engOutputBuffer函数可以截获MATLAB的输出,
     * 此字符串必须以NULL结尾  */
 
    buffer[BUFSIZE] = '\0';
    engOutputBuffer(ep, buffer, BUFSIZE);
    while (result == NULL) {
        char str[BUFSIZE+1];

        /* 获取用户的输入 */
        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(">> ");
 
        fgets(str, BUFSIZE, stdin);
      
        /* 执行用户输入的字符串  */
        engEvalString(ep, str);
        
        /* 在命令行中返回输出,前两个字符总是“>>”  */
        printf("%s", buffer+2);
        
        /*  获取计算结果 */
        printf("\nRetrieving X...\n");
        if ((result = engGetVariable(ep,"X")) == NULL)
          printf("Oops! You didn't create a variable X.\n\n");
        else {
        printf("X is class %s\t\n", mxGetClassName(result));
        }
    }
 
    /* 完毕,释放内存,关闭MATLAB引擎,退出  */
    printf("Done!\n");
    mxDestroyArray(result);
    engClose(ep);
    
    return EXIT_SUCCESS;
}

⌨️ 快捷键说明

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