Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Matrix read-write problem

mjv_aau
Beginner
943 Views
Hi all,

I would like to read some specific elements of an array stored on a file on the disk, i.e. a matrix. I know which rows and columns my elements are located at but I do not want to waste time to read every element before or after them (since the array is pretty huge). Does anyone know a fast way to move the pointer to these elements and read only them !

Thanks in advance.
0 Kudos
4 Replies
Arjen_Markus
Honored Contributor II
943 Views
That would depend on the storage format:
- If the file is structured as a direct-access file, that is, the records are all of the same length.
then open it with ACCESS = 'DIRECT' and use record number to read the record that contains
the information you want:

rec = ....
read( 10, rec = rec ) record_data

- If the file is a binary file without any record structure, then use ACCESS = 'STREAM'.
With the POS= key in the READ statement you can position the file pointer and read just what
you need:

pos = ....
read( 10, pos = pos ) record_data

The computations of the record number or the file position depend entirely on the layout of
the file. I am not going to speculate on that :)

Regards,

Arjen
0 Kudos
mjv_aau
Beginner
943 Views
Dear Arjen

I have applied the same as what you proposed, but it doesn't work.

For example, I simply generate a binary file by Matlab and try to read it by Fortran as below:

m file:

a=1:1:100;

fid=fopen('a.txt','w');

fwrite(fid, a', 'integer*4');

fclose(fid);

fortran file:

program data_read

implicit none

INTEGER::pos

real:: R

open(15, FILE='a.txt', ACCESS = 'STREAM')

pos=10

read (15,rec=pos) R

close (15)

print *, R

end program data_read

it shows a very small value close to zero on the screen.

0 Kudos
mecej4
Honored Contributor III
943 Views
> it shows a very small value close to zero on the screen

That is what one should expect in return for writing binary integers into a file and then reading the same file as if it contained 32-bit reals.
0 Kudos
Arjen_Markus
Honored Contributor II
943 Views
Yes, mecej4 is absolutely right: one of the "problems" of binary files is that they contain no inherent
information on the type of data. So if you write an integer to the file like in the MATLAB code then you should
read back an integer. This has nothing to do with the combination MATLAB-Fortran, but everything with the
way integers and reals are represented in bits or bytes and the nature of binary files.

What you need to do is mirror the data types when reading the file as closely as possible. Watch out for
strings - in Fortran the length of a string is defined by its declaration or length allocation (from F2003
onwards), in other languages it could depend on the content - I do not know where MATLAB stands in this
spectrum.

Regards,

Arjen

0 Kudos
Reply