MATLAB Mixed Programming Resources 1

zhaozj2021-02-12  136

Sender: Roy (China Farming), News District: MATLAB

Title: Compilation MEX Program in VC (ZZ)

Sending station: Red Fruit Garden (October 30, 2003, 11:08 Thursday), station letter

Compilation MEX program in VC

1. Purpose

Under normal circumstances, we all compile the MEX program in the MATLAB command line or the DOS command. The command used is

: MEX FileName.c This is a lot of inconvenient places:

a. Although MEX can also compile C MEX programs, its main frame is still C a. When the program has multiple modules

When you need to use the mex command multiple times, the operation is very troublesome

b. You cannot automatically create and maintain classes with ClassWizard-specific ClassWizard

c. You cannot write an application with MFC class library

d. Project management similar to VC cannot be easily performed

The programming environment of such a command line may greatly bind your imagination ... In fact, the method of solving the problem is simple.

The following is a VC6 environment as an example to explain how to compile the MEX program in the IDE.

2. Step

(1) Preparation (here, the path to matlab is: c: / matlab)

a. Create a library file MATLAB.LIB by matlab.def

Enter the C: / MATLAB / EXTERN / INCLUDE directory, generate matlib.lib with the lib command

C: /> cd / matlab / extern / incrude

C: / matlab / extern / include> lib /def::matlab.def /out:matlab.lib

Microsoft (R) Library Manager Version 6.00.8447

Copyright (c) Microsoft Corp 1992-1998. All Rights Reserved.

LIB: WARNING LNK4068: / Machine Not Specified; defaulting to ix86

CREANG LIBRARY MATLAB.LIB and Object Matlab.exp

C: / matlab / extern / incrude>

Warning information does not need it.

b. Modify MEX.H

This file is also in the C: / Matlab / Extern / Include directory

Find this line: void mexfunction

Replace with: __declspec (dllexport) Void Mexfunction

Saved as: MEX_VC.H

(2) Start VC, create an MFC AppWizard (DLL) program framework

(3) Set system options

a. Set the header file and library file path

Menu Tools-> Options-> Directories

Include Files: Add C: / Matlab / Extern / Include

Library Files: Add C: / Matlab / Extern / Include

b. Set the compilation connection option

Menu Project-> Settings

C / C -> PreProcessor definitions: Add MATLAB_MEX_FILE

Link-> Object / Library Modules: Add MATLAB.LIB

Note 1. Other optimization, debugging, and header files, library files and other options are adjusted

Note 2. The release version is set to Use in the General-> Microsoft Foundation Classes option.

MFC in a static library. Cause (4) Write a DLL main program

a. File name is to use .cpp as the extension, the first two lines must be:

#include "stdafx.h"

#include "mex_vc.h"

b. Write the MexFunction function, declare the following format: void mefunction

Int NLHS, MxArray * PLHS [],

INT NRHS, Const MxArray * PRHS [])

{

...

}

(5) Continue to write other programs like a DLL program of normal VC, add other modules

(6) Debug error, compile with F7, generate a DLL. My example:

-------------------- Configuration: Matwave - Win32 Release ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-

Compiableing resources ...

Compiable ...

Stdafx.cpp

Compiable ...

Matwave.cpp

Sample.cpp

MEX.CPP

GENERATING CODE ...

Linking ...

Creating Library Release / Matwave.lib and Object Release / Matwave.exp

Link: warning lnk4089: All references to "shell32.dll" discarded by / opt: re

Fly

LINK: WARNING LNK4089: ALL References to "comdlg32.dll" discarded by / opt: r

EF

Matwave.dll - 0 Error (s), 2 Warning (s)

Dachel, there are two warnings, ignore it. Try it in Matlab, but there must be illegal operation and abnormal retreat.

Psychological preparation.

In addition: If you want to recompile the DLL in Matlab, you need to execute: Clear MEX

The C or Fortran language program that can be called in Matlab is called the MEX file. MATLAB can directly treat the MEX file as its built-in function to call. The MEX file is a subroutine that dynamically links, and the MATLAB interpreter can automatically load and execute it. The MEX file has the following uses:

For a large number of existing C or Fortran programs, there is no need to rewrite Matlab-specific M file formats in MATLAB.

Sender: Roy (China Farming), News District: MATLAB

Title: Method for calling MATLAB in VC

Sending station: Red Fruit Park (November 09, 2003 14:53:14 Sunday), station letter

Matlab provides a variety of ways to mix programming with C / C

There are currently the following.

1. COM component programming.

In Matlab, call the COMTOOL tool, compile the .m file into a standard COM component.

This approach is the mode of MATLAB.

2. Use the MATLAB Addin in the VC to compile the .m file directly into an executable.

This is also a comparative standard practice. In the experiment, there is no problem.

The problem exists in this way is that the generated C language code can not be changed, and it is impossible to join your code.

If you do not call the graphical interface, you can join your own code.

For example: the main program generated is generally

INT Main (int Argc, const char * * argv) {

Return MClmain (Argc, Argv, MlxReadd, 0, & _Main_INFO);

}

Don't call the MCLMAIN function, but call it with a function of the original interface.

Void MlxReadd (int NLHS, MxArray * PLHS [], INT NRHS, MXARRAY * PRHS [])

Often. However, this is slightly to some initialization processes. Specifically, you can refer to Matlab help.

Automatically generated main program has done the following work.

1. Defines Persistent / Global Variables2. Initializes The Feval Function Table for Run-Time Feval Support

3. Performs Wrapper-Specific Initialization and Termination

4. Initializes the constant pools generated by Optimization

What I want to achieve is the following, I think the simplest, suitable for writing console procedures.

3. Write the main program directly, and then make the program's mix of the program.

Since Matlab does not promote this call, in version V6.5, there is no help. Refer to MATLAB6.1

Compiler

MIXING M-Files and C OR C or C (P110)

Example of the writing of the main program: main.c

#include

#include

#include "matlab.h"

// Here the statement will be called.

Void * mlfreadd (void);

Main (int Argc, char ** argv)

{

Pkginitialize (); / * Initialize the library of m-functions * /

MLFReadd (); / * Call function * /

Pkgterminate (); / * Terminate the library of m-functions * /

}

Just put this program and read.m file in a directory, compiled in matlab.

The compile command is:

MCC -B SGL -W LIBHG: PKG -T LINK: EXE -H MyPlot Main.c Libmmfile.mlib

This command is for functions that require graphics support.

If you don't need graphic support, the command is: (the recommended compilation option in the manual)

MCC -T -W LIB: PKG -T LINK: EXE -H MRANK MRANKP.C LIBMMFILE.MLIB

Note that the PKG here will be in response to the pkginitialize () in the main program.

The above is directly generated .EXE file

More common practice is to generate .c and .h files, compile in VC.

Step is:

Compiled .m file. Example MyPlot.m

% EXAMPLE: MyPlot.m

Function myplot (b)

A = B;

Plot (a);

Command is:

Mcc -t -l c -wllibhg: pkg -h myplot

(Note, I used graphics here, if not, it should be -wlib: pkg)

The generated files are:

MyPlot.h

myplot.c

Pkg.c

Pkg.h

Pkg.exports

Pkg.mlib

It is useful to all source files myplot.h, myplot.c, pkg.c, pkg.h.

Place your own main program main.c and the source file above in a directory.

Source program main.c

#include

#include

#include "matlab.h"

Void * mlfmyplot (mxaRray *);

Main (int Argc, char ** argv)

{

MxArray * n;

N = mlfscalar (25);

Pkginitialize (); / * Initialize the library of m-functions * /

MLFmyPlot (n);

Pkgterminate (); / * Terminate the library of m-functions * /}

2. Start compilation of VC6.0.

Set the header file search path and library file path

Under the menu Tools - Options-Directories, show directories for include files, then

Add to

Search path, Matlabroot is the installation path of Matlab on the machine:

Matlabroot / Extern / Include

Matlabroot / Extern / include / CPP

Then change the show directories for library file, add a search path:

Matlabroot / Extern / lib / win32

MATLABROOT / EXTERN / LIB / WIN32 / Microsoft / MSVC60

These options are set up, they apply for each project.

For each Project, set

Menu Project - Setting Under the Object / Library Modules, remove the original joins

KERNEL32.LIB User32.lib gdi32.lib advapi32.lib oleaut32.lib

Ole32.lib libmatlb.lib / NOLOGO libmx.lib libmat.lib libmwservices.lib Libme

x.lib libut.lib sgl.lib

(Note that the library here is found from the information given from the MCC compile, so it may be only to me.

Effective, actually

Plus the needs of the needs, refer to the configuration file, anyway, the library is those)

Plus, compile, and run.

(Only one point on the map, HEHE)

Here, if you need a graphic library, you need to build a bin directory in the directory where .exe is located.

From matlabroot / extern / include, figuremenubar.fig and firsttoolbar.fig to

bin. Otherwise there is no menu and toolbar

3) What is the use of .mcc, mex, mbuild?

: #Fangq (qianqian.fang@dartmouth.edu), 2002/6 / 22.Biggreen / Mathtools #

I have never been very clear about this problem. After reading the PDF help of Compiler, I know

Probably, I don't know if it is right:

MCC (generated C / CPP file) ----- M - MEX ------ MEX / DLL

| --- x - MBUILD ---- C / C Compiler ---- Independent Program

The MEX file is a compiled dynamic connection file, which needs to be implemented in matlab.

Is the execution speed than the M file, and if you don't want to provide M file source code, you can use

Compiled MEX / DLL file.

MBUILD converts MCC into C / C source code by calling the external C / C compiler

With the MATLAB's C / C math library, the graphic library link, get an executable executable.

Creating Matlab MEX-FILE

To create Executable Files from M-Files, You CAN Use MCC. MCC IS MATLAB TO C / C Compiler. It can compile m-files to executable files with exe or dll extension. For example:

Make a c translation and a mex-file for myfun.m: mcc-x myfun

Make a c translation and a standard-alone executable for myfun.m:

MCC -M myfun

Make A C Translation and a standard-alone executable for myfun.m:

MCC -P myfun

Make a c mex wrapper file from myfun1.m and myfun2.m:

MCC-W MEX -L C libmatlbmx.mlib myfun1 myfun2

Make a c translation and a standard-alone executable from myfun1.m and myfun2.m (use one MCC Call):

MCC -M myfun1 myfun2

But There is Another Way To Create Mex Files. In this way you have fulfull control of every function That You create and can Optimize their speted, memory, size etc.

The Components of a C MEX-File

The Source Code for a MEX-File Consists of Two Distinct Parts:

.

A gateway routine that interfaces the computational routine with MATLAB by the entry point mexFunction and its parameters prhs, nrhs, plhs, nlhs, where prhs is an array of right-hand input arguments, nrhs is the number of right-hand input arguments, plhs IS An Array of Left-Hand Output Arguments, And NLHS Is The Number of Left-Hand Output Arguments. The Gateway Calls The Computational Routine As a Subroutine.

In the gateway routine, you can access the data in the mxArray structure and then manipulate this data in your C computational subroutine. For example, the expression mxGetPr (prhs [0]) returns a pointer of type double * to the real data in the mxArray pointed to by prhs [0]. you can then use this pointer like any other pointer of type double * in C. After calling your C computational routine from the gateway, you can set a pointer of type mxArray to the data it returns. MATLAB is then able to recognize the output from your computational routine as the output from the MEX-file.The following C MEX cycle figure shows how inputs enter a MEX-file, what functions the gateway routine performs, and how outputs return to MATLAB.

Creating MEX-FILES IN VISUAL C

Run Visual C , select New ... from File menu. In opened dialog, select "Win32 Dynamic-Link Library". In wizard, select "A DLL that exports some symbols" and press finish. Now everything is ready for building a MEX -file!

Add Following Lines To Main Source Code:

#include "matlab.h" // Matlab API

#pragma comment (Lib, "libmx.lib")

#pragma comment (Lib, "libmat.lib")

#pragma Comment (Lib, "Libmex.lib")

#pragma comment (Lib, "Libmatlb.lib")

Add Matlab_mex_file preProcessor to Project Settings (Project -> Settings -> C / C -> General -> Preprocessor Definitions).

.... Create a text file and rename it to your_project.def your_project is name of your MEX-file your_project.def is a definition file for exporting symbols In this situation, you must export mexFunction Here is an example:

MEXFunction.def: Declares The Module Parameters for the DLL.

Library "computeprimes"

Description 'Computeprimes Windows Dynamic Link Library'Exports

Explicit Exports Can Go Here

MEXFunction

Now You Must Add Following Compiler Switch To Your Project (Project -> Settings -> Link -> General -> Project Options:

/Def :"./mexfunction.def "

EXAMPLE

IN this example, input argument is an in turnr Non-Complex Scalar (n) and output is a vector containing first n prime number. Name of mex-file is computeprimes. Syntax:

Y = computeprime (n)

Final Work:

#include "stdafx.h"

#include "matlab.h"

#include "mexfunction.h"

#pragma comment (Lib, "libmx.lib")

#pragma comment (Lib, "libmat.lib")

#pragma Comment (Lib, "Libmex.lib")

#pragma comment (Lib, "Libmatlb.lib")

// Return True IF N Is a Prime Number

Bool isprime (int N)

{

For (int i = 2; i <= n / 2; i )

{

IF (n% i == 0)

Return False;

}

Return True;

}

Void computeprimes (double * y, int N)

{

INDEX = 0, i = 2;

While (INDEX! = n)

{

IF (Isprime (i))

{

y [index] = i;

INDEX ;

}

i ;

}

}

Void Mexfunction (int NLHS, MxArray * pl Hs [], int NRHS, Const mxaRray * prHs [])

{

IF (NRHS! = 1)

{

MEXERRMSGTXT ("ONE Input Required.");

}

Else IF (NLHS> 1)

{

MEXERRMSGTXT ("Too Many Output Arguments");

}

/ * The Input Must Be a noncomplex scalar integer. * /

Int MROWS, NCOLS;

MROWS = MXGETM (PRHS [0]);

Ncols = mxGETN (PRHS [0]);

IF (! mxisdouble) || MXisComplex (PRHS [0]) ||

! (MROWS == 1 && ncols == 1))))

{

"" "Input Must Be a Noncomplex Scalar Integer.");

}

Double x, * y;

/ *

E.G.

* x = 4,

* Y = 2, 3, 5, 7

* /

x = mxgetscalar (PRHS [0]);

/ * Create Matrix for the return argument. * / Plhs [0] = MXCREATEDOUBLEMATRIX (MROWS / * 1 * /, (int) x, mxreal);

Y = mxgetpr (PLHS [0]);

// Call computeprimes Subroutines to Fill Vector of Primes

ComputePrimes (Y, (int) x);

}

3. Compiling M-File Into the MEX-FILE

3.1. TO CREATE A MEX-FILE from A M-File, your M-File Must Be Written As Function M-File.

IF you have a script m-file you must confert it to a function. TO Convert A Script to a Function SIMPLY Add A Function Line At The Top of the M-File (The Function Can Be Both - With and with wel serameters).

3.3. Enter the 'MCC' Command:

>> MCC -X Houdini

The -x Option IS Used In Case of M-File Compilation. This 'MCC' Command GeneRates:

A file named houdini.c containing MEX-file C source code. A file named houdini.h containing the public information. A file named houdini _mex.c containing the MEX-function interface (MEX Wrapper). A MEX-file named houdini. The Extension of The Executable Mex-File Depends of Your Platform, EG, ON The PC The File Is Named Houdini.dll.

'mcc' automatically invokes mex to create houdini.mex from houdini.c and houdini_mex.c. The Mex Utility Encapsulates The Appropriate C Compiler and Linker Options for Your System.

Note: Ignore Warning About Break Statement In Magic-function.

3.4. After Compiling, A Mex File Called Houdini.mexsol Must Be in Your Working Directory. This file can be used. This file.

>> x = houdini (4)

4.4. Finally, you will check The company by us.. '

Let US Choose The Flames.m File Is Stored In The Directory $ MATLAB / EXTERN / Examples / SGL.

Copy this file to your working Directory and Type:

- for a c

>> MCC -B SGL Flames.m- for A C

>> MCC -B SGLCPP Flames.m

http://stommel.tamu.edu/~baum/toolboxes.html // Matlab Toolbox List

MATLAB and C language interface

Northeast University Schrödinger (original) Please note the author information, URL, thank you

The conversion of matlab to the C language program can be completed by two ways, one is MATLAB's own C language translation MCC, the other is MATCOM developed by the original 3rd company Mathtools. The latter appears earlier, the function is far more powerful than Matlab's own translation, so MathTools has been acquired by MathWorks and has been integrated into newly launched MATLAB 6.0 (Release 12).

According to the point of view, both are not perfect, there is a large number of MATLAB functions and data types that cannot be compatible, so sometimes it will find that the simple MATLAB program is very embarrassed. The translated C procedure is hardly suitable for manual maintenance, and it will not be upgraded.

There are several incompatible places that cannot be tolerated. For example, the Eval () function is not compatible in c translation, the latest MATLAB 6 just dares to say some is already partially compatible, but it is still very compatible from the real compatibility. The road to go, there are many difficult technical difficulties that need to be overcome, and it is impossible to make a breakthrough in a short time. Another big problem is, well known, MATLAB's new control system toolbox defines a large number of LTI classes, and Matlab 5 will also allow the concept of classes and objects, which has taken a big step toward "object-oriented" programming. However, the translation of Matlab to C clearly supports the "object" data type, so there is almost no practical significance in the control system analysis and design (of course, there are other fields), so don't turn this conversion too Idealized.

From the speed of conversion, the program running speed is impossible because MCC and MATCOM computers along the program operation mechanism of MATLAB. Conversely, if you write a clear bottleneck portion in the MATLAB program, it can be greatly accelerated in accordance with the MEX format using the C language. In the "Scientific Operation Language Matlab 5.3 programming and application", the author has been explored in an example, and the MCC can be 50% faster, while the form of MEX may be hundreds of times faster.

〖Example〗 Fractal problem: From the initial point (X0, Y0), generate new points (X1, Y1) according to the formula below

Where the GI is a random number of evenly distributed intervals. Requirements from (X1, Y1) (X2, Y2), ... until 1,000,000 points (a bit exaggerated, but too little use of MATLAB measurement time). The program written by MTLAB can be downloaded to download the program written by MEX_C. Program call statement is: >> n = 1000000; v = rand (n, 1); tic; [x, y] = frac_tree (0, 0, v, n); TOC then test the speed, then think with MATCOM or MCC switches, try the speed. Question: How much is the MATCOM program in the end than the M function? I use MEX_C to achieve the speed of more than 100 times! Here are articles introduced, with MATcom VC can be 1.5 times (in other applications), according to others, for the district 1.5 times, you will not find yourself to find yourself to use Matcom.

In this way, the only advantage that Matlab to C conversion is that it can develop software with independent copyright. Therefore, I generally don't agree with such a conversion method to develop procedures, especially the way to deliberate MATLAB C. I believe: This method is generally employed unless necessary. This view is proposed, and the discussion is welcome. Matcom has two programs in BC and VC, and some articles have been included in the Matlab VC home. The author sees such software in the download area.

Given the link of a download area here

转载请注明原文地址:https://www.9cbs.com/read-7186.html

New Post(0)