Fortran: Difference between revisions

Jump to navigation Jump to search
102 bytes added ,  13 July 2020
→‎C++ function: Update function to work with Octave 5.2.0+
(fix name of fortran file)
(→‎C++ function: Update function to work with Octave 5.2.0+)
Line 8: Line 8:
=== C++ function ===
=== C++ function ===


{{Code|octave_file_io.cc: C++ function to load a matrix from an ASCII file in Octave native format|<syntaxhighlight lang="C" style="font-size:13px">
{{Code|octave_file_io.cc: C++ function to load a matrix from an ASCII file in Octave native format|<syntaxhighlight lang="CC">
// Octave header
#include <octave/oct.h>
#include <octave/ls-mat-ascii.h>
 
// Custom header containing the C compatible interface
#include <octave_file_io.h>
#include <octave_file_io.h>


//! Load a single matrix, stored in ASCII format, from a data file.
//!
//! @param file_name name of the data file.
//! @param data pointer to the read-in matrix stored as fortran vector
//!            (column-major order).
//! @param numel number of elements in @p data.


#include <octave/oct.h>
int octave_load (const char* file_name, double** data, int* numel)
#include <octave/ov.h>
#include <fstream>
#include <ls-oct-ascii.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>
#include <octave/load-save.h>
#include <octave/oct-map.h>
#include <cstring>
 
int octave_load (const char* filename, const char* varname, double** data, int* numel)
{
{
    
   // Define variable to hold the read data.
   string_vector argv (1);
   octave_value read_data;
  load_save_format format = LS_ASCII;


   install_types (); 
   // Read a plain ASCII matrix from data file.
  argv(0) = varname;
   std::ifstream in_file_stream (file_name, std::ios::binary);
 
  read_mat_ascii_data (in_file_stream, file_name, read_data);
   std::ios::openmode mode = std::ios::in | std::ios::binary;
   in_file_stream.close ();
   std::string fname (filename);


   std::ifstream file (fname.c_str (), mode);
   // Convert read data to numerical array (matrix).
    
   NDArray A = read_data.array_value ();
  octave_scalar_map m = do_load (file, fname, format, oct_mach_info::flt_fmt_unknown,
                                false, false, true, argv, 0, 1, 1).scalar_map_value ();


   file.close ();
   // Extract number of elements in matrix A.
  *numel = A.numel ();


   Array<double> M = m.contents (varname).array_value ();
   // Allocate memory to pointer to returned values.
  if (error_state)
  *data  = (double*) malloc (A.numel () * sizeof (double));
    return -1;


   *data = (double*) malloc (M.numel () * sizeof (double));
   // Copy the content of matrix A to data structure Fortran can handle.
  *numel = M.numel ();
  memcpy (*data, A.fortran_vec (), A.numel () * sizeof (double));


  memcpy (*data, M.fortran_vec (), *numel * sizeof (double));
   return 0;
 
   return 0;
}
}
</syntaxhighlight>}}
</syntaxhighlight>}}


=== Header file ===
=== Header file ===

Navigation menu