Как я могу сцепиться в MATLAB для оценки символьных производных из кода C?

Отказ от этих коммитов, вероятно, будет иметь некоторые негативные последствия для любого, кто извлекает из вашего хранилища. В качестве другого варианта вы можете рассмотреть возможность создания альтернативной ветки разработки, начиная с A2:

A1-->A2-->A3-->A4 (master/HEAD)
      \
       -->B1-->B2 (new-master/HEAD)

Сделать это так же просто, как

git branch new-master master~2
1
задан 3 revs, 2 users 100% 12 June 2009 в 17:40
поделиться

1 ответ

Вот рабочий пример на C вместе с Makefile для gcc \ Linux. Если кто-нибудь может предоставить инструкции по сборке для Windows или Mac, пожалуйста.

Сначала код C :

#define _GNU_SOURCE
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <engine.h>

int main (int argc, char *argv[])
{
    Engine    *engine;
    mxArray   *f;
    mxChar    *output;
    char      *input;
    char      *command;
    size_t     input_size;
    int        i;

    engine = engOpen ("matlab -nojvm");
    engEvalString (engine, "syms x");

    input = NULL;
    printf (">> "); getline (&input, &input_size, stdin);
    while (!feof (stdin)) {
        // remove the \n character
        input[strlen (input) - 1] = '\0';
        command = (char *)malloc (strlen (input) + 19);
        sprintf (command, "f=simple(diff(%s,x))", input);

        // execute the `diff` command on the user input expression
        engEvalString (engine, command);

        // the MATLAB engine does not understand the Symbolic Toolbox
        // therefore you have to convert the output expression into
        // some textual form (ccode,fortran,matlabFunction,latex)
        engEvalString (engine, "fstr=ccode(f)");
        f = engGetVariable (engine, "fstr");
        output = mxGetChars (f);

        // the expression is prefixed with some left-hand line (eg, "t0=")
        // so, discard everything to the left of the =, and display just
        // the derivative
        for (i = 0; output[i] != '='; i++);
        i++; // skip the =

        // `mxChar` is a 16-bit character, and `printf ("%ls")` is giving
        // me errors, so go through the string one character at a time, until
        // the semicolon is found (it is C-code), ignoring non-printable
        // characters along the way.
        for (; output[i] != ';'; i++) {
            if (isgraph (output[i])) {
                putchar (output[i]);
            }
        }
        putchar ('\n');
        printf (">> "); getline (&input, &input_size, stdin);
    }

    printf ("exiting...\n");
    engClose (engine);
    return EXIT_SUCCESS;
}

Если вам нужно использовать выражение, а не просто повторять его, вам придется написать свой собственный парсер. Но поскольку это простое выражение C (с функциями math.h ), оно довольно тривиально.

А вот мой Makefile, ничего особенного ... просто не забудьте правильно указать пути.

CC=gcc
CFLAGS=-O0 -g -Wall -I$(MATLAB_DIR)/extern/include
LDFLAGS=-L$(MATLAB_DIR)/bin/glnxa64 -leng -lmx -lmat -lut -licudata -licuuc -licui18n -licuio -lhdf5
MATLAB_DIR=/opt/matlab/2008a

%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@

diff_test: diff_test.o
    $(CC) $< -o $@ $(LDFLAGS)

И наконец, быстрая демонстрация:

# ./diff_test 
>> sin(x)
cos(x)
>> 2*x^2*tan(x)
2.0*x*(2.0*tan(x)+x+x*pow(tan(x),2.0))
>> log(x^2)
2.0/x
>> ^D
exiting...
2
ответ дан 3 September 2019 в 01:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: