Click here to Skip to main content
Click here to Skip to main content

Exporting/Importing Data To/From MATLAB

By , 20 Jan 2004
 

Introduction

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.

C MAT-File 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:

r Opens file for reading only; determines the current version of the MAT-file by inspecting the files and preserves the current version.
u Opens 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.
w Opens file for writing only; deletes previous contents, if any.
w4 Creates 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 "stdafx.h"
#include "mat.h"
#include "matlab.h"

#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]);
        return;
    }
    
    /* Read in each array. */
    pa = matGetNextVariable(pmat, &name);
    while (pa!=NULL)
    {
        /*
        * Diagnose array pa
        */
        printf("\nArray %s has %d dimensions.", name, 
               mxGetNumberOfDimensions(pa));
        
        //print matrix elements
        mlfPrintMatrix(pa);
        
        //get next variable
        pa = matGetNextVariable(pmat,&name);
                
        //destroy allocated matrix
        mxDestroyArray(pa);
    }
    
    matClose(pmat);
}

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 "stdafx.h"
#include "mat.h"
#include "matlab.h"

#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);
    matClose(pmat);
    
    mxDestroyArray(AA);
    mxDestroyArray(BB);
    mxDestroyArray(CC);
}

Enjoy!

License

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
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
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


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey26 Feb '12 - 19:52 
Nice
Generalreal-time analysismembersudhakardevaraya8 Feb '09 - 6:16 
Hi,
To all.
 

i am working on linux platform , i am doing a project its main task is developing a tool in c++ that can capture the real-time data network streams and find the bitrate of that stream , after that i have to calculate the mean and average for that streams in different locations.i have completed up to finding the bitrate and stored that bitrate information in a file.can anybody give the information how to read this real-time data in to MAT-LAB to find the mean and average .????
 
Thankyou for every one in advance!!!
 
Best regards
sudhakar devaraya
GeneralMatlab.h is not included in the extern->includememberjunYoungSon19 Jan '09 - 20:04 
#include "Matlab.h"
 
As written, I include the Matlab7->exter->include
 
but Matlab.h is not in the include folder...
 
How can i download the Matlab.h file...
 
Please answer to me
 
my e-mail address is destiny@etri.re.kr
 
Have a good day. !!
Questionsalam doostemanmemberRF_HAKIMI20 Nov '08 - 9:50 
man shahram hastam az mashhad
man mikham yek proje pardazesh tasvir ba matlab benevisam
wali az tarafi mikham mohitesho ba c++ builder ya c# kar konam
file ha ei ro ke gozashiti didam vali be tore kamel motevajeh na shodam.
 
mitooni be chan soal man javab bedi?
 
1- az kodoom ravesh estefade konam ? makhsoosan vaghti ba tasvir saro kar daram ?
 
2-che tor as in filah estefade conam ( class haei ke neveshti)?
 
3- age be kham ba c++ builder kar konam chetore kar konam ?( man dll sakhtam vali header filei ke be man dad be daradam nakhord . proto type function haro nadad )
 
bazam as matlabet mamnoon
sharmande zaban englisi man khub nist. Shucks | :->
QuestionHow to send a matlab stucture from one PC to another PC?membernarayana_12345615 Jul '07 - 22:14 
hi,
 
I want to send data in structure(matlab) format to another PC, through UDP or
TCP/IP. Is it possible? Both computers are using Matlab.
 
Thank you very much,
 
Narayana
 

Questionlibmatlb.libmembercukycuks20 Apr '07 - 6:53 
I need libmatlb.lib libmatlbmx.lib libmmfile.lib where can I find it? Thanks
GeneralC++ reading mat-filememberWambecq15 Apr '07 - 22:00 
Hi,

I have a problem in reading a mat-file by use of the C++ language (in
fact to make a S-funtion to use by simulink). For this I have a file
in which there is a variable called lookuptables. In there there is
are 4 structures arranged in the vertical direction. in each
structure there are 3 variables: Index,values and size. the size I
can read in but for the index and values I cannot. When I look in
matlab at these variables they look like for example: [10 45 19 56
87].

How do I read this in so I can use it?

Tom Wambecq
 
Tom Wambecq
QuestionHow does one do this in C#?memberGarth W9 Feb '07 - 23:53 
Not wanting to learn yet another language, how does one do this in c#?
Generalhamvatane shirazi aliememberhooshang Karami9 Dec '06 - 23:39 
Thank you Very Use Full
GeneralBug in readermemberrvangaal4 Dec '06 - 2:51 
Seems there's a small bug in the reader; you call 'mxDestroyArray' right after loading the next var. Easier perhaps would be a while() loop reading, printing and destroying the array.
 
www.racer.nl
www.dolphinitybv.com
GeneralRealtime writing of varsmemberrvangaal23 Nov '06 - 3:59 
Looking at the API, it doesn't seem possible to just write one array on the fly. Instead, you have to collect your data, then write it out.
Unfortunately I just tried a Simulink file writer block which generates a .mat file and bumped into a bug directly; from Simulink it works ok but a compiled C version (which just writes a header and then appends time/value double pairs at every timestep) writes a bogus file (loading it will give silly numbers).
 
Any idea of how I could efficiently implement realtime writing of a value? (buffering all the data seems like implementing a file all over again Frown | :( ).
 
Thanks for any tips, it just seems a bit non-realtime, the Matlab standard API.
Ruud van Gaal
 
www.dolphinitybv.com
GeneralRe: Realtime writing of varsmemberrvangaal1 Dec '06 - 5:13 
To follow up on myself, I now write an older Matlab version, which enables you to generate values on the fly, instead of having all values ready to write.
 
I'll include the useful functions, writing a header and appending values. Note that you will have to rewrite the header upon closing time! This will enable you to set the right array size.
Hope this helps anyone.
 
bool PMatlab::WriteHeader(int m,int n,cstring varName)
{
typedef enum { ELITTLE_ENDIAN, EBIG_ENDIAN } ByteOrder;
 
int one=1;
ByteOrder byteOrder = (*((char *)&one)==1) ? ELITTLE_ENDIAN : EBIG_ENDIAN;
int type = (byteOrder == ELITTLE_ENDIAN) ? 0: 1000;
int imagf = 0;
int name_len = strlen(varName) + 1;
 
if((fwrite(&type, sizeof(int), 1, fp) == 0) ||
(fwrite(&m, sizeof(int), 1, fp) == 0) ||
(fwrite(&n, sizeof(int), 1, fp) == 0) ||
(fwrite(&imagf, sizeof(int), 1, fp) == 0) ||
(fwrite(&name_len, sizeof(int), 1, fp) == 0) ||
(fwrite(varName, sizeof(char), name_len, fp) == 0))
{
return false;
} else
{
return true;
}
}
 
void PMatlab::Append(int t,double v)
// Append double value
{
if(!fp)return;
 
double tt=double(t)*0.001f; // Convert ms into secs
fwrite(&tt,1,sizeof(tt),fp);
fwrite(&v,1,sizeof(v),fp);
 
// Count # of elements
arrayCount++;
}

 
Ruud van Gaal
www.racer.nl
www.dolphinitybv.com
Questionmat file creatingmemberemresel9 Sep '06 - 7:42 
Selam;
Thanks for your articles please continue. I'm a new member. I work about MATLAB C compiler. I've written the function below and compile it with LCC. But after running the created EXE, result is not good. File contains no data(I understand from its size) and MATLAB cannot import resulting MAT file. Gives the error
"Error using->getfield"
"Error using->subsref"
"Invalid file name component"
I cant understand what is wrongSniff | :^) ? Could you please help me? I use MATLAB 6.1.0.450 (R12.1).
Thanks
Regards
Fuction is below;
 

void saveasMAT(int rows,int cols,double *input,char *output_name)
{MATFile *outmat=NULL;
mxArray *out=NULL;
printf("num of rows and cols is %d and %d\n",rows,cols);//xxxxxxxxxxxxxxxxxxxxxxx
out=mxCreateDoubleMatrix(rows,cols,mxREAL);
if(out==NULL)
{
printf("Real double matrix cannot be created and variable cannot be saved as MAT file\n");
exit(1);
}
printf("starting point of the matrix data is %d\n",input);//mxGetPr(out));//xxxxxxxxxxxxxxxxx
memcpy(mxGetPr(out), input, rows*cols*sizeof(double));
//printf("memcopy not failed in saveasMAT func");//xxxxxxxxxxxxxxxxxx
printf(" value in the input array is %f\n",*(input+300));//xxxxxxxxxxxxxxxxxxxxxx
printf(" value in the input array is %f\n",*(mxGetPr(out)+300));//xxxxxxxxxxxxxxxxxxxxxx
outmat=matOpen(output_name, "w");//xxxxxxxxxxxxxxxxxxoutput_name
if(outmat==NULL)
{
printf("MAT file cannot be opened and variable cannot be saved as MAT file\n");
exit(1);
}
matPutArray(outmat, out);
//matPutVariable(outmat,output_name, out);//if MATLAB version is 6.5 or greater
if (matClose(outmat) != 0)
{
printf("Error closing file %s\n",output_name);
exit(1);
}
printf("file has closed in saveasMAT func\n");//xxxxxxxxxxxxxxxxxx
 

//reopen to check if the file is created properly
outmat = matOpen(output_name, "r");//xxxxxxxxxxxxxxxxoutput_name
out = matGetNextArray(outmat);
//out = matGetNextVariable(outmat); //if MATLAB version is 6.5 or greater
if (out == NULL)
{
printf("Error reading in file %s\n", output_name);
exit(1);
}
printf(" value in the input array is %f\n",*(mxGetPr(out)+300));//xxxxxxxxxxxxxxxxxxxxxx
printf("starting point of the matrix data is %d\n",mxGetPr(out));//xxxxxxxxxxxxxxxxxxxxxxxxxx
//close the file again
if (matClose(outmat) != 0)
{
printf("Error closing file %s\n",output_name);
exit(1);
}
mxDestroyArray(out);
}
General#include "matlab.h"membersugi49520 Feb '06 - 23:29 
hi,
 
i found this article very helpful..but i have a few problems implementing it.first #include "matlab.h" is resulting in an error mssg. "unable to open include file "matlab.h"" though it's there in the same dir.
the purpose of my program is to extract an output from a matlab program and use it in C to (hopefully, eventually!) move a robo,so i need a realtime array of variables from matlab..is it possible?
please help.
i'm not a software expert (or anything!), so pleae reply in layman terms.
thankyou.
 
suganya
General: #include "matlab.h"memberabhinavp198614 Feb '10 - 22:36 
Hi
I am facing the same problem
Please any body can help me, how we can include mat.h & matlab.h headers files.
 
Thanks n Regards
Saurabhi
GeneralquestionmemberGabriyel10 Jan '06 - 20:46 
hi,
 
great article posted at codeproject.
 
i'm try to figure out how to run my simulink model with it communicating to an external program. is writing an s-function block that makes use of shared memory a good idea?
 
do you know any simulink block or toolkit that can accelerate this?
 
thanks very much.
 
gab
 
Live simply, simply live.
GeneralRe: questionmemberA. Riazi10 Jan '06 - 21:30 
Hi,
Unfortunately, I didn't work with simulink in detail and have no idea about what you want.
 
Best regards,
A. Riazi

GeneralGood example abovememberTAN THIAM HUAT22 Nov '05 - 19:11 
thanks Riazi for his good work, this is a splendid example, clear and consise.
It is able to pass variables from both Matlab and C++ and vice versa.
 
how about more than 2 dimension variables?
example
a=rand(3,4,2)
 

thanks.
 
-- modified at 1:25 Wednesday 23rd November, 2005
GeneralEXE from m.filememberRafid97420 Nov '05 - 1:34 
Salam
How can I convert m.file into exe. file (Independent executable file), which doesn't depend on MATLAB environment to work.
 
Regards
 
Salam
GeneralRe: EXE from m.filememberjsnpg28 Oct '08 - 16:31 
you're able to use the function of -mcc
further details, refer to matlab, help mcc Smile | :)
QuestionHow can I create a mat-file in linux?memberTa Xuan Hung29 Sep '05 - 20:05 
I want to make an application which can export its variables in mat-file.
Please help me!
 
h
GeneralUndeclared identifiermemberhailconan18 Sep '05 - 18:36 
First at all, Thx about this artical...
 
I copied the librarry and *.h files to your project after I have it from this artical, but when I tried to compile it I got this Error for variables A, B, and C
 

'A' : undeclared identifier
'B' : undeclared identifier
'C' : undeclared identifier
GeneralRe: Undeclared identifiermemberrvangaal1 Dec '06 - 3:16 
That's a typo; change the AA/BB/CC variables into A/B/C.
 
http://www.dolphinitybv.com
http://www.racer.nl
Generalinclude DLLs in commercial softwarememberTriac28 Feb '05 - 2:22 
Hi,
I'd like to know if it is possible to include Mathworks' DLLs (libeng.dll, libmat.dll, ...) in a commercial product and distribute them with it. Should I pay for some license?
 
Thanks
QuestionWhy "Entry Point Not Found"?sussBenjamin shi22 Feb '05 - 4:49 
Nice article! It is quite helpful for me to understand how to use mat.
 
While I try to run the demo, I met the following problem:
 
Entry Point Not Found
 
The procedure entry point matGetNextVariable could not be located in the dynamic link library libmat.dll.
 
I knew it is not a problem of the demo code as I met the same error while using the code example from matlab. But I can not identify what's wrong. Could you give any suggestion?
 
Ben
Confused | :confused:

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

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