[Matlab + C/C ++] Reading and writing binary files (pay attention to the data storage sequence)

Source: Internet
Author: User

[Matlab + C/C ++] Reading and writing binary files (pay attention to the data storage sequence)
Introduction

Because Matlab is simple and convenient, it has been applied in many fields: audio processing, image processing, and numerical computing. Although MATLAB is easy to operate, its execution speed is usually low due to its language interpretation mechanism. C/C ++ is generally considered to be an efficient advanced programming language. If we combine MATLAB and C/C ++, we may be able to get a compromise between simplicity and execution speed. The general form of this combination is: MATLAB is responsible for the vast majority of work, C/C ++ is responsible for the implementation of some key parts, the specific method in myPrevious blog posts.

When processing some data, it may involve reading and writing files. If MATLAB is used to store the data as a mat file, it is difficult for other programs to read the data. If you save the data as a text file, the file parsing process will become longer. Fortunately, MATLAB can read and write binary files in custom formats. Almost all programming languages (including C/C ++) Support reading and writing binary files. This article describes how to use MATLAB and C/C ++ to read and write binary files.

Prerequisites

MATLAB and C/C ++ do not use the same rules to store matrix data.! When combining MATLAB and C/C ++, pay attention to this point: C/C ++ stores data by row; MATLAB stores data by column. For example, suppose we have a matrix of 2 rows and 3 columns, a total of 2 × 3 = six elements. Assume that the data is as follows:
M = ??? 147258369 ???.

 
In MATLAB, M The storage sequence in the memory is. the storage sequence in C/C ++ is 1, 2, 3, 4, 5, 6, 7, 8, 9. therefore, the parsing results of MATLAB and C/C ++ are different for the same piece of data in the memory. Pay special attention to this in the actual development process.

 

MATLAB writes a matrix to a binary file

MATLAB provides four functions to read and write binary files:fopen(...),fread(...),fwrite(...),fclose(...).

The following example shows how to read and write binary files:

Example 1: store the double-precision matrix as a single-precision floating-point number to a binary file

% Generate A matrix of two rows and three columns of double-precision floating point number type A = rand (2, 3); % open 'test in binary write mode ('W') in the current working directory. dat 'fid = fopen ('test. dat ', 'w'); % write the elements of matrix A to the binary file fwrite (fid, A, 'singles') associated with fid as single-precision floating point numbers '); % Close fclose (fid) for the file associated with fid );

Example 2: read data from MATLAB as a single-precision floating-point number

% Open 'test. dat 'fid = fopen ('test. dat ', 'R'); % read six elements from the binary file associated with the fid. Each element is parsed with a single precision floating point type B = fread (fid, 2*3, 'singles'); % Close fclose (fid) for the file associated with fid );

In instance 2, B is a 6 × If you want to obtain A matrix of 1 in A format similar to that of instance 1, you can do this:B = reshape(B, 2, 3)

C. Read Binary data

C reads binary data in a similar way as MATLAB.

Example 3: Read test. dat of instance 1 in C Language

// Complete C code # include
  
   
# Include
   
    
Int main () {int I; char * filename = "test. dat "; float data [6]; FILE * fs = fopen (filename," r "); fread (void *) data, sizeof (float), 6, fs ); fclose (fs); // display data for (I = 0; I <6; I ++) {printf ("% f \ n", data [I]);} return 0 ;}
   
  

The output result of instance 3 is consistent with that of B read in instance 2. If you use MATLAB to reshape B in instance 2, B will become A storage structure similar to A in instance 1. The difference between A and B is only that their data types are different. When using data in instance 3, if you want to index the elements in column j of row I like MATLAB, you must transpose the access!

If there are a lot of follow-up operations in C and most of your important work is done in C, we recommend that you write operations in MATLAB to change the columns of the matrix (not the concatenation transpose) and then write the data. The modification is as follows:

fwrite(fid, A.', 'single');
C ++ reads binary files

The fstream class is required to read binary files using C ++. The example is as follows:

Instance 4: Use C ++ to read test. dat written by instance 1

// Complete C ++ Code # include
    
     
# Include
     
      
# Include
      
       
Using namespace std; int main () {float data [6]; string filename = "test. dat "; ifstream fs; fs. open (filename, ios_base: binary | ios_base: in); fs. read (reinterpret_cast
       
        
(Data), sizeof (float) * 6); fs. close (); for (int I = 0; I <6; I ++) {cout <data [I] <endl;} return 0 ;}
       
      
     
    
Summary

Using MATLAB and C/C ++ can quickly develop algorithms and obtain a program with fast execution speed.

When using MATLAB and C/C ++ in combination, pay attention to the data storage sequence.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.