out of memory error while reading binary file

24 views (last 30 days)
Ricky on 9 Aug 2013
Commented: Wave on 18 Apr 2020
Hello Everyone,
I am reading a binary file whose size is 644 MB. For reading the binary file I use the following command
[data,count] = fread(fileId, '*uint8');
When I start my MATLAB and type memory in the command window I get the following reponse.
Maximum possible array: 1150 MB (1.205e+09 bytes)
but when I read my binary file I get an out of memory error . I think it is because the fread function creates a column vector data whose size exceed the maximum possible array size.
Can someone help me how to read in a big binary file without facing the memory error. The contents of my binary file is reading from sensor being read through LAN port.

Answers (2)

Jan on 9 Aug 2013
Edited: Jan on 9 Aug 2013
It looks like FREAD allocates the memory in chunks with a growing buffer. This can exhaust 1 GB of free RAM easily for 640 MB of data. Try this:
Info = dir(FileName);
FID = fopen(FileName, 'r');
[data, count] = fread(fileId, [1, Info.bytes], '*uint8');
Then FREAD knows the size of the required input buffer.
But on the other hand it would be easy for FREAD to check the file size, when the dimensions are not specified. If the above method really works, send an enhancement request to TMW and ask for a proper pre-allocation in FREAD.
A general problem remains: You have only a very small amount of free RAM. Using a 64 bit version and installing further GBs is the best solution.
Wave on 18 Apr 2020
Hey Jan,
the problem is still there (Matlab 2019b) with the pre-allocation problem.
Thank you for your solution. It works quiete good with fread(fileId, [1, Info.bytes], '*uint8');

Sign in to comment.

Rodney Thomson
Rodney Thomson on 9 Aug 2013
Change your format specifier to 'uint8=>uint8'
This says: "my data is uint8 AND I want to store it in a uint8 array"
Otherwise MATLAB jus tassumes it should read a uint8 value and put it in a double. Which is 8 times the size, or 4.8GB in the case of your array!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!