What's the most basic way to format a 2D matri

2019-07-29 18:02发布

问题:

So I have an i by j matrix of doubles in C++ that I want to read into an IDL program.

Lets say that the matrix is called data, with size ROWS by COLS, and name string saved to filename. And I just write the values out in a stream to a binary file.

ofstream myfile (filename, ios::binary);
if(myfile.isopen())
{
  for (int i = 0; i < ROWS; i++){
     for (int j=0; j < COLS; j++){
          myfile<<data.at(i,j);
}
myfile.close();

I then want to read it back into IDL but I'm new to working with binary in IDL and following the documentation has gotten me here but it's not working.

function read_binmatrix, filename, ROWS, COLS, thetype

    mat = READ_BINARY(filename,DATA_TYPE=thetype,DATA_DIMS=[ROWS-1,COLS-1])
    return, mat

end
 ...
 ...
matrix = read_binmatrix(file2,num_rows,num_cols,5)

...but I get this error as output.

% READ_BINARY: READU: End of file encountered. Unit: 100, File:
...
% Execution halted at: READ_BINMATRIX     21 
...

回答1:

 myfile<<data.at(i,j); 

writes text to the file, not binary data. To write the numbers in binary format use std::ofstream::write():

 myfile.write(reinterpret_cast<char*>(&data.at(i,j),sizeof(decltype(data.at(i,j))));