Write matrix with Matlab and Read with C?

4 ビュー (過去 30 日間)
John
John 2017 年 3 月 27 日
編集済み: James Tursa 2017 年 3 月 27 日
I have a matrix (100 rows and 5 columns) that want to write it as binary and read with C code in the way that I can read it in C row-by-row (5 numbers a time).
How can this be coded with Matlab and C?
Thanks.

回答 (1 件)

James Tursa
James Tursa 2017 年 3 月 27 日
編集済み: James Tursa 2017 年 3 月 27 日
Use fopen, fwrite, fread.
EXAMPLE:
m-code: xbinary_create.m
x = 1:5;
fid = fopen('xbinary.bin','w');
fwrite(fid, x, 'double');
fclose(fid);
C-mex code: xbinary_read.c
#include "mex.h"
#include <stdio.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
FILE *fp;
char *fname;
double d;
int i, n;
if( nrhs == 2 && mxIsChar(prhs[0]) && mxIsNumeric(prhs[1]) ) {
fname = mxArrayToString(prhs[0]);
fp = fopen(fname,"r");
mxFree(fname);
if( fp != NULL ) {
n = mxGetScalar(prhs[1]);
for( i=0; i<n; i++ ) {
fread( &d, sizeof(d), 1, fp );
mexPrintf("%g\n",d);
}
fclose (fp);
} else {
mexErrMsgTxt("Unable to open file");
}
}
}
Sample run:
>> mex xbinary_read.c
>> xbinary_create
>> xbinary_read('xbinary.bin',5)
1
2
3
4
5
CAVEAT:
If you are writing and reading a 2D matrix, then be advised that MATLAB stores such data column-wise, whereas C stores such data row-wise. That is, if you have a 2D C array like "double x[3][4]", then it will be stored in memory by rows. Whereas if a variable is size 3x4 in MATLAB, it will be stored in memory by columns.
Bottom line is if you want to read the data in C by rows, you should write it out that way from MATLAB. Fortunately this is easy to do. Simply transpose the matrix first, and then write that transposed matrix out to the file via the above code.
  1 件のコメント
John
John 2017 年 3 月 27 日
Can you please have an example in both matlab writting and c readding? Thanks, James!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by