MATLAB Examples

Write and Read Binary Files in Simulink

Create a binary file with a custom header using the Binary File Writer block. Write data to this file. Read the header and data using the Binary File Reader block.


Write the Data

Specify the file header in the File header parameter of the Binary File Writer block as struct('A',[1 2 3 4],'B','x7'). The block writes the header first, followed by the data to the ex_file.bin file. The data is a noisy sine wave signal with a frequency of 100 Hz containing 1000 samples per frame. The sample rate of the signal is 1000 Hz. Set the Time span of the Time Scope block to 1 second.

Open the model.

writeModel = fullfile(matlabroot,'examples','dsp','writeData');

Run the model to write the data to ex_file.bin. Alternatively, view the data in a time scope.


Read the Data

Read the data in ex_file.bin file using the Binary File Reader block. The data is read as a single channel (column) containing multiple frames, where each frame has 1000 samples. View the data in a time scope.

Specify the header using the File header parameter in the reader. If the exact header is not known, you must at least specify the prototype of the header, that is, its size and data type. In this example, the header prototype is struct('A',[0 0 0 0],'B','-0') which has the same format as the header structure.

Open the model.

readModel = fullfile(matlabroot,'examples','dsp','readData');

Run the model to read the data. Alternatively, view the data in a time scope.


The output data in both the timescopes matches exactly. Once the processing is complete, close the models.