23 ビュー (過去 30 日間)
Karthik Krishnasamy 2017 年 2 月 1 日
I am new to Matlab and i have a question. I read a bindary file using the below command. Since i don't have the source code to the write binary file, i would like to understand the below commands to regenerate the source code.
end
My question: In the while loop, fread(fid,3) & fread(fid,110) - what these function will do?
##### 2 件のコメント表示非表示 1 件の古いコメント
Karthik Krishnasamy 2017 年 2 月 1 日
Thanks, could you share some example

サインインしてコメントする。

### 回答 (2 件)

Massimo Zanetti 2017 年 2 月 7 日

The fread function read data in binary format, thus sequences of 0s and 1s. Therefore, you can read raw data just as a sequence of 0s and 1s, or you can divide it into words (bytes) and give these words a numerical meaning which is not binary, but for example decimal. Let me give you an example:
Let us first save into a binary file called example.bin the numbers 7 and 15 as unsigned integers of 8bits
%open a file with the write permission (create new file)
fileID = fopen('example.bin','w');
%write numbers 7 and 15 as uint8 with left-most significant digit (big-endian)
fwrite(fileID,[7,15],'uint8','ieee-be');
%close file
fclose(fileID);
If we read this file using the same format of 8bit unsigned integer, the fread will return the same data as we saved:
%open the save binary file
fileID = fopen('example.bin');
%read TWO numbers of type unsigned 8bit integer
%close file
fclose(fileID);
A =
7 15
However, the same data can be read in other formats! We now set fread input parameters to read this data in a raw format, i.e., just as a sequence of 0s and 1s. Therefore, one bit at a time. Since data were saved in 8bit words, let us read two times a bunch of 8 bits:
%open file
fileID = fopen('example.bin');
%read the first EIGHT bits as unsigned integer bits (i.e., 0 or 1)
%read the the following EIGHT bits
fclose(fileID);
B1 =
0 0 0 0 0 1 1 1
B2 =
0 0 0 0 1 1 1 1
The first 8 bits encode the number 7 in binary notation, the others 15. This is the way fwrite stores the data. So, when using fread function, it is important to be aware of the TYPE of data we are reading (e.g., uint8, uint16, etc), the size this data occupy for each encoded character and the number of characters we want to read.
Check out the fread help page.
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Guillaume 2017 年 2 月 7 日
I'm not sure you're going to get very far if you can't understand the simple code your posted with the help of the documentation that Massimo linked to.
The code
1. attempts to read one byte
2. if that is succesful, then do all of the following:
3. skip 3 bytes
4. read 6 single precision floating point numbers
5. skip 110 bytes
7. go back to step 1
The code is badly written anyway. The 6 float read should be done in one go into a single matrix rather than in numbered variables. And of course, the loop overwrites the previously read variable each step.
##### 1 件のコメント表示非表示 なし
Karthik Krishnasamy 2017 年 2 月 8 日