Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As <a href="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819">Bill the Lizard</a> wrote you can use fread to load the data into a vector. I just want to expand a little on his answer. </p> <h3>Reading Data</h3> <pre><code>&gt;&gt; fid=fopen('data.bin','rb') % opens the file for reading &gt;&gt; A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A. </code></pre> <p>The commands <em>fopen</em> and <em>fread</em> default to Little-endian[1] encoding for the integers. If your file is Big-endian encoded you will need to change the <em>fread</em> to</p> <pre><code>&gt;&gt; A = fread(fid, count, 'int16', 'ieee-be'); </code></pre> <p>Also, if you want to read the whole file set </p> <pre><code>&gt;&gt; count=inf; </code></pre> <p>and if you want to read the data into matrix with <em>n</em> columns use</p> <pre><code>&gt;&gt; count=[n inf]; </code></pre> <h3>Writing Data</h3> <p>As for witting the data to a file. The command, <em>fwrite</em>, in <a href="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819">Bill's</a> answer will write to a binary file. If you want to write the data to a text file you can use <em>dlmwrite</em></p> <pre><code>&gt;&gt; dlmwrite('data.csv',A,','); </code></pre> <h3>References</h3> <p>[1] <a href="http://en.wikipedia.org/wiki/Endianness" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Endianness</a></p> <h3>Update</h3> <ol> <li><p>The machine format (IE, <em>ieee-be</em>, <em>ieee-le</em>, <em>vaxd</em> etc.) of the binary data can be specified in either the <em>fopen</em> or the <em>fread</em> commands in Matlab. Details of the supported machine format can be found in Matlab's documentation of <em>fopen</em>. </p></li> <li><p><a href="https://stackoverflow.com/users/4928/scott-french">Scott French's</a> comment to <a href="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819">Bill's answer</a> suggests reading the data into an int16 variable. To do this use</p> <pre><code>&gt;&gt; A = int16(fread(fid,count,precision,machineFormat)); </code></pre> <p>where <em>count</em> is the size/shape of the data to be read, <em>precision</em> is the data format, and <em>machineformat</em> is the encoding of each byte.</p></li> <li><p>See commands <em>fseek</em> to move around the file. For example, </p> <pre><code>&gt;&gt; fseek(fid,0,'bof'); </code></pre> <p>will rewind the file to the beginning where <em>bof</em> stands for <em>beginning of file</em>.</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload