MATLAB Answers

Stand alone C file

21 views (last 30 days)
sasha
sasha on 4 Dec 2014
Answered: Ryan Livingston on 5 Dec 2014
I have my matlab code which is working, but a little slow. I want to write it for C, but I have an error that comes up when I use the Code Generation Rediness test. I am using
y(1) = dlmread('filename.txt');
and
y(n) = dlmwrite('newfilename.txt');
in a for loop that goes from 1 to n. The Readiness test says that these won't work, but I don't know how to read these text files into the code in a way that will be able to convert into C. The files are 201x201 arrays.
If anyone can help me out, it would be much appreciated

Answers (2)

Ryan Livingston
Ryan Livingston on 5 Dec 2014
One way to do this is to use coder.ceval and the C runtime functions. Alternatively, the MATLAB functions FOPEN, FREAD, FCLOSE are all supported for code generation. So you could use those to read the file in to a MATLAB string, and then use coder.ceval to call sscanf to parse the string.
There is an example in the doc that demonstrates reading a file using coder.ceval.
If you want to use the C runtime, and supposing that the file is named data.txt and that it contains 201-by-201 (201 lines of 201) space-delimited doubles (e.g. output from dlmwrite('data.txt',reshape(1:(201^2),201,201),'delimiter',' '); ) you could use something like:
function y = parsefile
%#codegen
coder.cinclude('<stdio.h>');
f = coder.opaque('FILE*','NULL');
f = coder.ceval('fopen', cstr('data.txt'),cstr('r'));
assert(f ~= coder.opaque('FILE*','NULL'), 'Failed to open file');
% Parse file
N = 201;
y = coder.nullcopy(zeros(N,N));
fmt = cstr('%lf ');
for k = 1:numel(y)
coder.ceval('fscanf', f, fmt, coder.wref(y(k)));
end
coder.ceval('fclose',f);
% File was read in row-major order so transpose
y = y.';
%--------------------------------------------------------------------------
function s = cstr(st)
% Append a \0 (NUL) character to produce a C
% string from a MATLAB string
s = [st, 0];
Just run:
codegen parsefile
y = parsefile_mex;
to use it.

Youssef  Khmou
Youssef Khmou on 4 Dec 2014
Edited: Youssef Khmou on 5 Dec 2014
If you mean reading a file with C, then you need to use pointer as the following, with apriori knowledge of array dimensions :
#include <stdio.h>
int main(void)
{
int x=201;
int y=201;
FILE *yourfile=NULL;
char c;
int i=0,j=0;
double M[x][y];
yourfile = fopen("filename.txt","r");
c = getc(yourfile) ;
while (c!= EOF)
{
M[i][j]=c;
j++;
c = getc(fp);
if(j==201){
i++;
j=0;
}
}
fclose(yourfile);
}

Community Treasure Hunt

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

Start Hunting!