using fread() to read part of a file

28 views (last 30 days)
Ahmed
Ahmed on 26 Jun 2015
Commented: Stephen23 on 26 Jun 2015
Hi everyone I came with another frustrating question at least for me which is: I have a matrix of [10000,26] stored in a file using fwrite() function. This means I have to use fread() to read from that file. Well the problem is that when I tried to load part of the file, lets say [100,26], the fread() keeps reading the first column. So I built a side program to see how the fread() behaves
count=1;
zz=zeros(10000,26);
for i=1:10000
for j=1:26
zz(i,j)=count;
count=count+1;
end
end
vidbin=fopen('test.bin','wb');
fwrite(vidbin,zz,'float');
fclose(vidbin);
I found out when I tried to load a portion of the file as
vidbin=fopen('test.bin','rb');
myarr=fread(vidbin,[100,26],'float');
fclose(vidbin);
The array myarr is not as suppose to be. it looks like 1 2601 . . . 65001 27 2627 . . . 65027 . . . myarr= . . . . . . 2575 5175 67575 It appears as if the fread() reads the first column in zz[] and divides it along the columns of myarr[] as the first row should be [1 2 3 ... 26].
How can I make fread() reads the required part of the file that I want the way I want? Waiting for ideas and solutions, please.
  1 Comment
Stephen23
Stephen23 on 26 Jun 2015
Edited: Stephen23 on 26 Jun 2015
Note that it is more robust to avoid using i and j for variable names, as these are both names of the inbuilt imaginary unit.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 26 Jun 2015
Edited: Stephen23 on 26 Jun 2015
The documentation for fread states that "fread populates A in column order", so when you specify the size of A it keep reading along the "columns" of the file, whereas you are wanting it to stop reading after a certain number of rows.
To resolve the issue, try transposing the matrix (untested):
fwrite(vidbin, zz.', 'float');
and then specifying how many columns, not rows:
myarr = fread(vidbin, [26,100], 'float').';
  2 Comments
Ahmed
Ahmed on 26 Jun 2015
Thank you very much Stephen Cobeldick for your swift answer. I did what you've suggested and it was part of the solution. After transposing the original matrix, fread() kept reading in columns but this time the columns are in order [1, 2, 3,...] not as before. So I reshaped it as [26,100] and then transposed it again to get the final array as supposed to. It is kind of tricky, but we have to to what it takes.
Thank you again for helping me finding the solution
Stephen23
Stephen23 on 26 Jun 2015
I am glad that it works!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!