Click here to Skip to main content
13,344,765 members (48,220 online)
Click here to Skip to main content
Add your own
alternative version


30 bookmarked
Posted 20 Jan 2004

Exporting/Importing Data To/From MATLAB

, 20 Jan 2004
Rate this:
Please Sign up or sign in to vote.
Exporting/Importing Variables Data To/From MATLAB Using C MAT-File API
<!-- Add the rest of your HTML here -->


Sometimes it is required that you export calculated data from one environment to another. The same thing occurred when you are working with C/C++ and also MATLAB environment. In this case, some tools must already exist to act as a bridge for both environments. MATLAB C MAT-File APIs are a group of functions for reading/writing a MAT compatible file from C/C++ environments that can be read by MATLAB. This means that if you save your variables data (result of some calculation) from MATLAB, you can read them from a C program and continue your calculation and if you compute something in your program and want to save them in a file that MATLAB can read them without any problem, you can use these APIs.


MATLAB C MAT-File APIs are those functions for opening a file and saving data in a compatible format for using them in MATLAB. The first step to use these functions is including mat.h header file. Notice that if you want to use MATLAB built-in functions, you must include matlab.h header file too. The second step is adding MATLAB libraries to your project. The required library is libmat.lib. If you use another MATLAB APIs, add their libraries too. For example, if you use mlfPrintMatrix function to print matrix elements, you must add libmx.lib, libmatlb.lib and libmmfile.lib.

Below are some of basic C MAT-File APIs with their description and syntax:

MATFile *matOpen(const char *filename, const char *mode);

Arguments: filename is name of file to open, mfp is a pointer to MAT-file information and mode is file opening mode.

Legal values for mode listed in Table 1:

rOpens file for reading only; determines the current version of the MAT-file by inspecting the files and preserves the current version.
uOpens file for update, both reading and writing, but does not create the file if the file does not exist (equivalent to the r+ mode of fopen); determines the current version of the MAT-file by inspecting the files and preserves the current version.
wOpens file for writing only; deletes previous contents, if any.
w4Creates a MATLAB 4 compatible MAT-file.

Description: This function allows you to open MAT-files for reading and writing. matOpen opens the named file and returns a file handle, or NULL if the open fails. You must close the file by using matClose function.

char **matGetDir(MATFile *mfp, int *num);

Arguments: mfp is a pointer to MAT-file information. num is address of the variable to contain the number of mxArray variables in the MAT-file.

Description: This function allows you to get a list of the names of the mxArray variables contained within a MAT-file. matGetDir returns a pointer to an internal array containing pointers to the NULL-terminated names of the mxArrays in the MAT-file pointed to by mfp. The length of the internal array (number of mxArrays in the MAT-file) is placed into num. The internal array is allocated using a single mxCalloc and must be freed using mxFree when you are finished with it. matGetDir returns NULL and sets num to a negative number if it fails. If num is zero, mfp contains no arrays. MATLAB variable names can be up to length mxMAXNAM, where mxMAXNAM is defined in the file matrix.h.

mxArray *matGetVariable(MATFile *mfp, const char *name);
mxArray *matGetNextVariable(MATFile *mfp, const char *name);

Arguments: mfp is a pointer to MAT-file information and name is name of mxArray to get from MAT-file.

Description: matGetVariable allows you to copy an mxArray out of a MAT-file.
matGetVariable reads the named mxArray from the MAT-file pointed to by mfp and returns a pointer to a newly allocated mxArray structure, or NULL if the attempt fails.
matGetNextVariable allows you to step sequentially through a MAT-file and read all the mxArrays in a single pass. The function reads the next mxArray from the MAT-file pointed to by mfp and returns a pointer to a newly allocated mxArray structure. MATLAB returns the name of the mxArray in name.

Use matGetNextVariable immediately after opening the MAT-file with matOpen and not in conjunction with other MAT-file functions. Otherwise, the concept of the next mxArray is undefined.

matGetNextVariable returns NULL when the end-of-file is reached or if there is an error condition.

In both functions, be careful in your code to free the mxArray created by this routine when you are finished with it.

int matPutVariable(MATFile *mfp, const char *name, const mxArray *mp);

Arguments: mfp is a pointer to MAT-file information. name is name of mxArray to put into MAT-file. mp is an mxArray pointer.

Description: This function allows you to put an mxArray into a MAT-file. matPutVariable writes mxArray mp to the MAT-file mfp. If the mxArray does not exist in the MAT-file, it is appended to the end. If an mxArray with the same name already exists in the file, the existing mxArray is replaced with the new mxArray by rewriting the file. The size of the new mxArray can be different than the existing mxArray. matPutVariable returns 0 if successful and nonzero if an error occurs.

Importing Variables Data From MATLAB

For saving variables in MATLAB, just use save command. for example:

save myFile

By entering the above command, MATLAB will save all of variables in its workspace in a file named myFile.mat. For saving only some variable, use save command like:

save myFile X Y Z

with above command, MATLAB saves only X, Y and Z variables. Now we want to use C MAT-File APIs to read myFile.mat and extract all of saved variables. Below is our C code to doing this:

#include <span class="code-string">"stdafx.h"</span>
#include <span class="code-string">"mat.h"</span>
#include <span class="code-string">"matlab.h"</span>

#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmatlb.lib")
#pragma comment(lib, "libmmfile.lib")

void main(int argc, char **argv)
    MATFile *pmat;
    const char* name=NULL;
    mxArray *pa;
    /* open mat file and read it's content */
    pmat = matOpen("myFile.mat", "r");
    if (pmat == NULL) 
        printf("Error Opening File: \"%s\"\n", argv[1]);
    /* Read in each array. */
    pa = matGetNextVariable(pmat, &name);
    while (pa!=NULL)
        * Diagnose array pa
        printf("\nArray %s has %d dimensions.", name, 
        //print matrix elements
        //get next variable
        pa = matGetNextVariable(pmat,&name);
        //destroy allocated matrix

Exporting Variables Data To MATLAB

It's time to do reverse task. In other hand we want to calculate something and save data to a file that MATLAB can read it. To import data from a MAT-File to MATLAB environment, one must use load command:

load myFile

Load command, load workspace variables from a file located on your disk. Following source code, define some mxArray varialbe and then save them in a file. This file can be called from MATLAB environment.

#include <span class="code-string">"stdafx.h"</span>
#include <span class="code-string">"mat.h"</span>
#include <span class="code-string">"matlab.h"</span>

#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmatlb.lib")
#pragma comment(lib, "libmmfile.lib")

void main(int argc, char **argv)
    MATFile *pmat;
    //now create a new mat-file and save some variable/matrix in it
    double dbl1[]={1.1, 4.3, -1.6, -4, -2.75};
    double dbl2[]={-4.9, 2.3, -5};
    mxArray *AA, *BB, *CC;

    A=mxCreateDoubleMatrix(1, 5, mxREAL);
    B=mxCreateDoubleMatrix(1, 3, mxREAL);

    //copy an array to matrix A and B
    memcpy(mxGetPr(A), dbl1, 5 * sizeof(double));
    memcpy(mxGetPr(B), dbl2, 3 * sizeof(double));

    C=mlfConv(A, B);        //convolution
    //opening TestVar.mat for writing new data
    pmat=matOpen("TestVar.mat", "w");
    matPutVariable(pmat, "A", A);
    matPutVariable(pmat, "B", B);
    matPutVariable(pmat, "C", C);



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


About the Author

A. Riazi
CEO Misbah3Com
Iran (Islamic Republic of) 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...


Comments and Discussions

QuestionCompiler error!! Pls help Pin
DhanushkaKul19-Jan-16 12:56
memberDhanushkaKul19-Jan-16 12:56 
AnswerRe: Compiler error!! Pls help Pin
rvangaal6-Dec-17 1:26
memberrvangaal6-Dec-17 1:26 
QuestionIs it necessary for Matlab to be installed? Pin
Abhishek Durvasula20-Apr-15 3:05
memberAbhishek Durvasula20-Apr-15 3:05 
AnswerRe: Is it necessary for Matlab to be installed? Pin
rvangaal6-Dec-17 1:27
memberrvangaal6-Dec-17 1:27 
GeneralMy vote of 5 Pin
manoj kumar choubey26-Feb-12 20:52
membermanoj kumar choubey26-Feb-12 20:52 
Generalreal-time analysis Pin
sudhakardevaraya8-Feb-09 7:16
membersudhakardevaraya8-Feb-09 7:16 
GeneralMatlab.h is not included in the extern-&gt;include Pin
junYoungSon19-Jan-09 21:04
memberjunYoungSon19-Jan-09 21:04 
Questionsalam doosteman Pin
RF_HAKIMI20-Nov-08 10:50
memberRF_HAKIMI20-Nov-08 10:50 
QuestionHow to send a matlab stucture from one PC to another PC? Pin
narayana_12345615-Jul-07 23:14
membernarayana_12345615-Jul-07 23:14 
Questionlibmatlb.lib Pin
cukycuks20-Apr-07 7:53
membercukycuks20-Apr-07 7:53 
GeneralC++ reading mat-file Pin
Wambecq15-Apr-07 23:00
memberWambecq15-Apr-07 23:00 
QuestionHow does one do this in C#? Pin
Garth W10-Feb-07 0:53
memberGarth W10-Feb-07 0:53 
AnswerRe: How does one do this in C#? Pin
rvangaal6-Dec-17 1:29
memberrvangaal6-Dec-17 1:29 
Generalhamvatane shirazi alie Pin
hooshang Karami10-Dec-06 0:39
memberhooshang Karami10-Dec-06 0:39 
GeneralBug in reader Pin
rvangaal4-Dec-06 3:51
memberrvangaal4-Dec-06 3:51 
GeneralRealtime writing of vars Pin
rvangaal23-Nov-06 4:59
memberrvangaal23-Nov-06 4:59 
GeneralRe: Realtime writing of vars Pin
rvangaal1-Dec-06 6:13
memberrvangaal1-Dec-06 6:13 
Questionmat file creating Pin
emresel9-Sep-06 8:42
memberemresel9-Sep-06 8:42 
General#include "matlab.h" Pin
sugi49521-Feb-06 0:29
membersugi49521-Feb-06 0:29 
General: #include "matlab.h" Pin
abhinavp198614-Feb-10 23:36
memberabhinavp198614-Feb-10 23:36 
GeneralRe: : #include "matlab.h" Pin
Member 858127419-Sep-13 19:08
memberMember 858127419-Sep-13 19:08 
Generalquestion Pin
Gabriyel10-Jan-06 21:46
memberGabriyel10-Jan-06 21:46 
GeneralRe: question Pin
A. Riazi10-Jan-06 22:30
memberA. Riazi10-Jan-06 22:30 
GeneralGood example above Pin
TAN THIAM HUAT22-Nov-05 20:11
memberTAN THIAM HUAT22-Nov-05 20:11 
GeneralEXE from m.file Pin
Rafid97420-Nov-05 2:34
memberRafid97420-Nov-05 2:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 21 Jan 2004
Article Copyright 2004 by A. Riazi
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid