0

I am trying to read experimentally collected data into MATLAB via a text file. The data are all integers in eight columns separated by white space.

I want to open the file, read in the data, and then reshape into the representative array.

So, I have:

fileID = fopen('String name of file');
A = fread(fileid);
B = reshape(A, (length(A) / 8), 8);

By default, fread assumes the data are doubles, but when I try to specify integers, such as fread(fileid, inf, 'int'), the data still come out with the wrong values.

The data were output by a Java program as 'int' and were generated in a Linux environment, but are now in Windows (only MATLAB license I have). I assume this is an issue of specifying the correct data type for the fread but I'm not sure.

Any ideas?

1
  • 1
    Use dlmread or csvimport (disclaimer: my contribution) to read delimited data instead of fread Commented Sep 16, 2013 at 17:40

2 Answers 2

1

I don't know about using fread, but textscan should work:

% Open file
fid = fopen('file.txt');

% Scan 8 columns of numeric values
tmp = textscan( fid, repmat('%f ', [1 8]));

% Close file handle
fclose(fid);

% Convert to int and join columns into matrix
data = int32(cat(2, tmp{:}));
Sign up to request clarification or add additional context in comments.

1 Comment

This achieves the desired effect, but Praetorian's suggestion of 'dlmread' is a little more straight-forward.
0

Use *int instead of int. Possibly try int32 or another platform-independent syntax. From the manual for fread:

By default, numeric and character values are returned in class 
'double' arrays. To return these values stored in classes other 
than double, create your PRECISION argument by first specifying 
your source format, then following it by '=>', and finally 
specifying your destination format. If the source and destination 
formats are the same then the following shorthand notation may be 
used:

    *source

which means:

    source=>source

Also note that you can use the simplified reshape syntax:

B = reshape(A, [], 8);

2 Comments

That's not producing the desired result. Too much data to be certain, but it looks to have the same effect as just using 'int'
Hmmm, A should be an int with that syntax. Try A = fread(fileid,'*int32'); or use another platform independent syntax like uint32 or int16 etc. Set a breakpoint right after fread to see check the variable type. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.