12,400,938 members (59,931 online)
alternative version

675K views
78 bookmarked
Posted

Solving Engineering Problems Using MATLAB C++ Math Library

, 21 Jul 2003
 Rate this:
Using MATLAB C++ Math Library to solve engineering problems

Introduction

In the previous article, we studied how can use MATLAB C API to solve engineering problems. In this article I will show you how can use MATLAB C++ math library. The MATLAB® C++ Math Library serves two separate constituencies: MATLAB programmers seeking more speed or complete independence from interpreted MATLAB, and C++ programmers who need a fast, easy-to-use matrix math library. To each, it offers distinct advantages.

MATrix LABoratory

MATLAB is abbreviation of Matrix Laboratory. This means every computation was performed in matrix form. In other hand every data type wrapped in matrix form and every function take these matrix as an input argument.

For example you want to multiply to polynomial as follow:

`A = (3x<SUP>2</SUP> + 5x + 7) (4x<SUP>5</SUP> + 3x<SUP>3</SUP> - x<SUP>2</SUP> + 1)`

You can use two matrices for coefficients of any polynomials:

`[3 5 7]` for `(3x2 + 5x + 7)` and `[4 0 3 -1 0 1]` for `(4x5 + 3x3 - x2 + 1)`, using `conv` function, we can obtain coefficients of result:

`conv([3 5 7], [4 0 3 -1 0 1]): A = [12 20 37 12 16 -4 5 7]`

means:

`A = 12x<SUP>7</SUP> + 20x<SUP>6</SUP> + 37x<SUP>5</SUP> + 12x<SUP>4</SUP> + 16x<SUP>3</SUP> - 4x<SUP>2</SUP> + 5x + 7`

C++ Math Library

The MATLAB C++ Math Library consists of approximately 400 MATLAB math functions. It includes the built-in MATLAB math functions and many of the math functions that are implemented as MATLAB M-files. The MATLAB C++ Math Library is layered on top of the MATLAB C Math Library. The major value added by this C++ layer is ease of use.

The MATLAB C++ Math Library is firmly rooted in the traditions of the MATLAB runtime environment. Programming with the MATLAB C++ Math Library is very much like writing M-files in MATLAB. While the C++ language imposes several differences, the syntax used by the MATLAB C++ Math Library is very similar to the syntax of the MATLAB language. Like MATLAB, the MATLAB C++ Math Library provides automatic memory management, which protects the programmer from memory leaks.

Every matrices represented by `mwArray` class, a data type introduced by MATLAB for constructing a matrix. As I said before, every data must be wrapped in a matrix form in other hand: `mwArray.`

One C++ prototype supports all the possible ways to call a particular MATLAB C++ Math Library function. You can reconstruct the C++ prototype by examining the MATLAB syntax for a function. In the following procedure, the MATLAB function `svd() `is used to illustrate the process.

MATLAB Syntax

```s = svd (X)
[U, S, V] = svd (X)
[U, S, V] = svd (X, 0)```

In this example, the prototype that corresponds to [U, S, V] = svd (X, 0) is constructed step-by-step. Until the last step, the prototype is incomplete.

Adding the Output Arguments

1. Subtract out the first output argument, U, to be the return value from the function. The data type for the return value is `mwArray`.

`mwArray svd(`
2. Add the remaining number of output arguments, S and V, to the prototype as the first, second, etc., arguments to the function. The data type for an output argument is `mwArray`*.

`mwArray svd (mwArray* S, mwArray* V,`

Adding the Input Arguments

1. Add the number of input arguments to the prototype, X and Zero, one after another following the output arguments. The data type for an input argument is `mwArray`.

```mwArray svd (mwArray* S, mwArray* V, const mwArray& X,
const mwArray& Zero);```

The prototype is complete.

How to Translate a MATLAB Call into a C++ Call

This procedure translates the MATLAB call `[U, S, V] = svd (X, 0) `into a C++ call. The procedure applies to library functions in general. Note that within a call to a MATLAB C++ Math Library function, an output argument is preceded by &; an input argument is not.

1. Declare input, output, and return variables as `mwArray` variables, and assign values to the input variables.

2. Make the first MATLAB output argument the return value from the function.
`U = svd (`
3. Pass any other output arguments as the first arguments to the function.
`U = svd (&S, &V,`
4. Pass the input arguments to the C++ function, following the output arguments.
`U = svd (&S, &V, X, 0);`

The translation is complete.

Note that if you see [] as a MATLAB input argument, you should pass `mwArray()` as the C++ argument. For example,

`B = cplxpair (A, [], dim)`

becomes

`B = cplxpair (A, mwArray(), dim);`

mwArray class

The `mwArray` class public interface is relatively small, consisting of constructors and destructor, overloaded new and delete operators, one user-defined conversion, four indexing operators, the assignment operator, input and output operators, and array size query routines. The `mwArray`’s public interface does not contain any mathematical operators or functions.

Constructors

The `mwArray` interface provides many useful constructors. You can construct a `mwArray` object from the following types of data: a numerical scalar, an array of scalars, a string, an `mxArray*`, or another `mwArray` object.

`mwArray()`

Create an uninitialized array. An uninitialized array produces warnings when passed to MATLAB C++ Math Library functions. If an array is created using this default constructor, a value must be assigned to it before passing it to a MATLAB C++ Math Library function.

To create an empty double matrix that corresponds to [] in MATLAB, use the
function `empty()`.

`mwArray (const char *str)`

Create an array from a string. The constructor copies the string.

`mwArray(int32 rows, int32 cols, double *real, double *imag = NULL)`

Create a `mwArray` from either one or two arrays of double-precision floating-point numbers. If two arrays are specified, the constructor creates a complex array; both input arrays must be the same size. The data in the input arrays must be in column-major order, the reverse of C++’s usual row-major order. This constructor copies the input arrays.

Note that the last argument, imag, is assigned a value of NULL in the constructor. `imag` is an optional argument. When you call this constructor, you do not need to specify the optional argument.

`mwArray (const mwArray& mtrx)`

Copy a `mwArray`. This constructor is the familiar C++ copy constructor, which copies the input array. For efficiency, this routine does not actually copy the data until the data is modified. The data is referenced through a pointer until a modification occurs.

`mwArray (const mxArray* mtrx)`

Make a `mwArray` from an `mxArray`*, such as might be returned by any of the routines in the MATLAB C Math Library or the Application Program Interface Library. This routine does not copy its input array, yet the destructor frees it; therefore the input array must be allocated on the heap. In most cases, for example, with matrices returned from the Application Program Interface Library, this is the desired behavior.

`mwArray (double start, double step, double stop)`

Create a ramp. This constructor operates just like the MATLAB colon ( operator. For example, the call `mwArray(1, 0.5, 3)` creates the vector `[ 1, 1.5, 2, 2.5, 3 ]`.

`mwArray (int32 start, int32 step, int32 stop)`

Create an integer ramp.

`mwArray (const mwSubArray & a)`

Create an `mwArray` from an `mwSubArray`. When an indexing operation is applied to an array, the result is not another array, but an `mwSubArray `object. An `mwSubArray `object remembers the indexing operation. Evaluation of the operation is deferred until the result is assigned or used in another expression. This constructor evaluates the indexing operation encoded by the `mwSubArray `object and creates the appropriate array.

```mwArray (double) ```
Create a 1-by-1 `mwArray` from a double-precision floating-point number.

```mwArray (int) ```
Create an `mwArray` from an integer.

Table 1 shows `mwArray `constructors in brief.

Constructor Creates Example

`mwArray()`

Uninitialized array

`mwArray A;`

`mwArray (const char *)`

String array

`mwArray A ("MATLAB Rules");`

`mwArray (int32, int32, double*, double*)`

Complex array

```double real[] = { 1, 2, 3, 4 }; double imag[] = { 5, 6, 7, 8 }; mwArray A(2,2,real,imag);```

`mwArray (const mwArray&)`

Copy of input array

```mwArray A = rand(4); mwArray B (A);```

`mwArray (const mxArray*)`

Copy of mxArray*

```mxArray *m = mlfScalar(1); mwArray mat (m);```

`mwArray (double, double, double)`

Ramp

`mwArray A(1.2, 0.1, 3.5);`

`mwArray (int32, int32, int32)`

Integer ramp

`mwArray A(1, 2, 9);`

`mwArray (const mwSubArray&)`

Array from subarray (used in indexing)

```mwArray A = rand(4); mwArray B(A(3,3));```

`mwArray (double)`

Scalar double array

`mwArray A(17.5);`

`mwArray (int)`

Scalar integer array

`mwArray A(51);`

Mathematical Functions

Below is a list of useful mathematical functions of MATLAB C++ math library:

 plus, minus mtimes, mpower acos, asin conv conj dec2bin, dec2hex disp fft, fft2 linspace max, min roots rot90

Using C++ Math Library

To add support of MATLAB C++ Math Library follow these instructions:\

1. Add following line at the end of stdafx.h

`#include <span class="code-keyword"><matlab.hpp></span>`

matlab.hpp is interface of MATLAB C++ math library. Add directory of MATLAB interface files (*.hpp) to Visual Studio (Tools -> Options -> Directories). For example: x:\matlab\extern\include\cpp, where x is drive letter of matlab path.

2. Add desired libraries to your project (In this example, libmatpm.lib)

3. Compile your project!

Sample Program

```#include <span class="code-string">"stdafx.h"
</span>
#include <span class="code-string">"matlab.hpp"        //Interface of MATLAB CPP Math Library
</span>

//Add C++ Math Library to project
#pragma comment(lib, "libmatpm.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmatlb.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmmfile.lib")
#pragma comment(lib, "libmatpm.lib")

int main(int argc, char* argv[])
{
mwArray A, B, C;

A = magic(mwArray(5));
B = transpose(A);     //B=A'

C = plus(A,B);      //C = A + B;
C = minus(A,B);     //C = A - B;
C = mtimes(A,B);    //C = A * B;

double arr1[]={3.0, 2.0, 5.0, -1.0};
double arr2[]={8.0, 1.0, 3.0, -2.0};
mwArray D(1, 4, arr1);
mwArray E(4, 1, arr2);

C = D * E;          //4*4 matrix mwArray
F(0.0, 0.1, 5.0);   //create double ramp
F = F * transpose(F);

A.Print("A");	//Magic Matrix, Order=5
C.Print("C");
D.Print("D");

return 0;
} ```

Known Problems

• Compiler reports error when compiling matlab.hpp:
```c:\matlab\extern\include\cpp\matmtxif.h (16):
fatal error C1083: Cannot open include file strstream.h.
No such file or directory.```

This error is due to missing preprocessor definitions in the MSVC environments. In order to alleviate this problem, the following definitions must be added to the project file for the application:

• MSVC
• MSWIND
• IBMPC
• D__STDC_

Add these preprocessors to your project: Project->Settings->C/C++->Preprocessor definitions.

• Linker reports error when linking MATLAB library files:
```LINK : warning LNK4098: defaultlib "MSVCRT" conflicts with use of other libs;
use /NODEFUALTLIB:library
.\ex1.exe : fatal error LNK1169: one or more multiply defined symbols found

To resolve this problem change project settings to build a Multithread Dll in the Runtime Library. Do this by following these instructions:

• Selecting Project from the main menu
• Selecting Settings
• Clicking on C/C++ tab
• Selecting Code Generation in the Category pulldown menu
• In the Runtime Library field selecting Multithread Dll ("Debug Multithread Dll" will not work)
• Click OK
• Rebuild your project

References

Enjoy!

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

 CEO Misbah3Com Iran (Islamic Republic of)
I was born in Shiraz, a very beautiful famous city in Iran. I started programming when I was 12 years old with GWBASIC. Since now, I worked with various programming languages from Basic, Foxpro, C/C++, Visual Basic, Pascal to MATLAB and now Visual C++.
I graduated from Iran University of Science & Technology in Communication Eng., and now work as a system programmer for a telecommunication industry.
I wrote several programs and drivers for Synthesizers, Power Amplifiers, GPIB, GPS devices, Radio cards, Data Acqusition cards and so many related devices.
I'm author of several books like Learning C (primary and advanced), Learning Visual Basic, API application for VB, Teach Yourself Object Oriented Programming (OOP) and etc.
I'm winner of January, May, August 2003 and April 2005 best article of month competetion, my articles are:

You can see list of my articles, by clicking here

You may also be interested in...

 First PrevNext
 problem Member 883511028-May-12 21:02 Member 8835110 28-May-12 21:02
 Damet Garm mohsensafa28-Apr-12 7:18 mohsensafa 28-Apr-12 7:18
 My vote of 5 manoj kumar choubey26-Feb-12 19:51 manoj kumar choubey 26-Feb-12 19:51
 Matrix division in Matlab M.Siyamalan22-May-11 11:46 M.Siyamalan 22-May-11 11:46
 trying to send data from VC++ to Matlab adityapatel_200624-Feb-10 22:58 adityapatel_2006 24-Feb-10 22:58
 Using Matlab C++ Library With Visual Studio 2005 or 2008 Tolga Ozaslan25-May-09 10:20 Tolga Ozaslan 25-May-09 10:20
 please help me to solve this question!!!!!!!!!!!!! ziey8730-Jan-09 23:22 ziey87 30-Jan-09 23:22
 Getting error sdas_ju30-Nov-08 9:21 sdas_ju 30-Nov-08 9:21
 Matlab C++ :Unhandled exception in ex1.exe(NTDLL.DLL):0xC0000005:Access Violation error daisy0225-Jun-08 0:23 daisy02 25-Jun-08 0:23
 matlab to exe file caty9-May-08 21:17 caty 9-May-08 21:17
 Wants Help in Matalb Programming mahmoodhashmi10-Apr-08 0:36 mahmoodhashmi 10-Apr-08 0:36
 How to call matlab functions from C++ [Matlab 7 r14] jstachera29-Oct-07 14:28 jstachera 29-Oct-07 14:28
 problem by openning a image(using "imread") azbanafsh29-Oct-07 8:43 azbanafsh 29-Oct-07 8:43
 Problem when compile kebitmat_f11-Oct-07 15:50 kebitmat_f 11-Oct-07 15:50
 error linking Arif W.P.10-Oct-07 4:11 Arif W.P. 10-Oct-07 4:11
 Re: error linking Member 451405710-Sep-08 6:02 Member 4514057 10-Sep-08 6:02
 creating veriables of type mwArray dilaverv30-Jul-07 6:09 dilaverv 30-Jul-07 6:09
 Ambiguity smzhaq18-Jul-07 4:57 smzhaq 18-Jul-07 4:57
 How to get results smzhaq8-Jul-07 7:07 smzhaq 8-Jul-07 7:07
 Re: How to get results smzhaq8-Jul-07 7:52 smzhaq 8-Jul-07 7:52
 Re: How to get results A. Riazi8-Jul-07 23:16 A. Riazi 8-Jul-07 23:16
 creating a C++ shared library from M-files Ttania29-Dec-06 8:15 Ttania 29-Dec-06 8:15
 matlab.hpp? xb2111-Dec-06 10:47 xb211 1-Dec-06 10:47
 Re: matlab.hpp? A. Riazi1-Dec-06 10:52 A. Riazi 1-Dec-06 10:52
 Re: matlab.hpp? xb2111-Dec-06 11:06 xb211 1-Dec-06 11:06
 Re: matlab.hpp? A. Riazi1-Dec-06 11:14 A. Riazi 1-Dec-06 11:14
 Re: matlab.hpp? xb2111-Dec-06 11:24 xb211 1-Dec-06 11:24
 Re: matlab.hpp? Arris77-Dec-06 9:55 Arris7 7-Dec-06 9:55
 Re: matlab.hpp? m3janitha4-Mar-09 2:05 m3janitha 4-Mar-09 2:05
 Need Help with invoking MATLAB 7 from C++ Lax Pillutla28-Nov-06 20:53 Lax Pillutla 28-Nov-06 20:53
 Re: Need Help with invoking MATLAB 7 from C++ A. Riazi28-Nov-06 23:15 A. Riazi 28-Nov-06 23:15
 Intergrating to existing C++ project kevinyeudoi21-Aug-06 7:26 kevinyeudoi 21-Aug-06 7:26
 Re: salam A. Riazi27-Jun-06 0:34 A. Riazi 27-Jun-06 0:34
 dev-cpp using rmarfe19-Jun-06 5:40 rmarfe 19-Jun-06 5:40
 calling MATLAB (R14) functions from C++ newbie1000020-May-06 19:16 newbie10000 20-May-06 19:16
 Help: Extern Errors UJ_Student18-May-06 1:36 UJ_Student 18-May-06 1:36
 Re: Help: Extern Errors A. Riazi18-May-06 7:04 A. Riazi 18-May-06 7:04
 Re: Help: Extern Errors UJ_Student22-May-06 7:58 UJ_Student 22-May-06 7:58
 My project in MFCAppWizard(dialog based) r_win9-May-06 12:10 r_win 9-May-06 12:10
 Re: My project in MFCAppWizard(dialog based) A. Riazi10-May-06 2:27 A. Riazi 10-May-06 2:27
 Re: My project in MFCAppWizard(dialog based) r_win16-May-06 11:49 r_win 16-May-06 11:49
 Re: My project in MFCAppWizard(dialog based) A. Riazi17-May-06 3:33 A. Riazi 17-May-06 3:33
 Re: My project in MFCAppWizard(dialog based) r_win18-May-06 6:43 r_win 18-May-06 6:43
 Re: My project in MFCAppWizard(dialog based) A. Riazi18-May-06 8:18 A. Riazi 18-May-06 8:18
 Instantiating mwArray from mxArray koriandr6-Mar-06 7:57 koriandr 6-Mar-06 7:57
 Re: Instantiating mwArray from mxArray A. Riazi7-Mar-06 1:01 A. Riazi 7-Mar-06 1:01
 Re: Instantiating mwArray from mxArray JitenderRawal29-May-07 5:46 JitenderRawal 29-May-07 5:46
 Matlab 7.1SP3 labrary, Visual Studio .NET soloio8-Feb-06 8:35 soloio 8-Feb-06 8:35
 Re: Matlab 7.1SP3 labrary, Visual Studio .NET A. Riazi8-Feb-06 10:27 A. Riazi 8-Feb-06 10:27
 Last Visit: 31-Dec-99 18:00     Last Update: 26-Jul-16 20:35 Refresh 12345 Next »

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.