How do I read an ASCII data file from stand-alone code generated by the MATLAB Compiler?

4 views (last 30 days)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 28 Jan 2010
The MATLAB Compiler-generated version of LOAD can only load MAT-files. Thus, you will need to use the FSCANF function along with the RESHAPE and transpose (') functions if you wish to read ASCII data files from a stand-alone application.
The RESHAPE function is needed because of the nature of the operation of the FSCANF function. FSCANF reads the file in a row-wise manner and fills the resulting matrix in a column-wise manner. For example, if you have an ASCII data file (let's name it data.txt), that looks like the following:
1 2 3 4 5
0 9 8 7 6
11 22 33 44 55
66 77 88 99 00
You can read the file using the following command:
x=fscanf(fid, '%d', [4 5])
The value of x in the MATLAB workspace is:
x =
1 5 7 33 77
2 0 6 44 88
3 9 11 55 99
4 8 22 66 0
When you look carefully, the numbers are all there but the order is a little bit scrambled.
Instead of reading the data into a 4 by 5 matrix, read the data file into a vector and then reshape it. For example:
x=fscanf(fid, '%d');
x=reshape(x, 5, 4)';
These two lines will give you:
x =
1 2 3 4 5
0 9 8 7 6
11 22 33 44 55
66 77 88 99 0
Here is an example MATLAB function that utilizes FSCANF and RESHAPE to read in an ASCII data file:
function out=read_ascii(filename, m, n)
fid=fopen(filename);
out=fscanf(fid, '%d');
out=reshape(out, [n m])';
return
Run the MATLAB file with the following command:
x=read_ascii('data.txt', 4, 5)
x =
1 2 3 4 5
0 9 8 7 6
11 22 33 44 55
66 77 88 99 0
The read_ascii function above is good if you know the size of the data in the text file before hand. A more generalized version of this function would be as follows:
function a = loadAscii(filename)
fid = fopen(filename);
if fid==-1
error([filename ': File does not exist']);
end
numlines = 0;
try
while( 1 )
tline = fgetl(fid);
if ~ischar(tline), break, end
numlines=numlines+1;
end
fseek(fid, 0, 'bof');
a = fscanf(fid,'%g',[numlines inf]);
[r c] = size(a);
% The next two steps are required since MATLAB reads the data in column major format
% and fscanf reads data in row major format
a = reshape(a,c,r);
a = a'
fclose(fid);
catch
fclose(fid);
error([filename ': Error while reading file']);
end

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!