fprintf does not save all the data

6 ビュー (過去 30 日間)
Vahid Askarpour
Vahid Askarpour 2021 年 10 月 4 日
回答済み: Walter Roberson 2021 年 10 月 4 日
In my workspace, I have a 1x1 struct named modes. It has three fields called x,y,z. Each field is 1x46000 and each cell is a number in exponential format. I would like to save the x array to a .dat file. So I did the following
id = fopen('modes_x.dat', 'wt+');
for i = 1:size(modes.x,1)
fprintf(fid, '%s\r\n', modes(i,1).x)
end
fclose(fid)
Only 20566 values are saved to file. Beyond 20566, there are about 18000 zeros followed by more non-zero numbers. Somehow, fprintf stops saving data when it hits the zeros.
I tried replacing %s with %e but the output is blank.
Does anyone know what I am missing here? Too bad there is no option in the menu bar for such a simple task.
Thank you,
Vahid

採用された回答

Walter Roberson
Walter Roberson 2021 年 10 月 4 日
When you use fprintf() with a %s format and ask to display a numeric value, then:
  • if the value to be converted is a non-negative integer, including 0, then uint16() of the value would be taken, and that would be used as the character code. These days, mostly that would act as a Unicode character code, but that could vary depending on exactly how the file was opened. For example, integer 65 would be come character code 65, which is the character code for 'A' so A return linefeed would be output. In this case, the code would not output the characters '6' '5'
  • otherwise, if the value has a fraction or is negative, %s does not warn but instead uses a %.6e format.
In the case of 0, char(0) would be emitted, and the \r\n would be emitted. But binary 0 in particular can mess up displays, depending how it is coded.

その他の回答 (1 件)

Vahid Askarpour
Vahid Askarpour 2021 年 10 月 4 日
My apologies for the typo. In the first line, "id" should be "fid".
There are two attachments to this message. The Matlab window shows the actual code.
The output screenshot shows the vi output of modes.dat showing the number of lines as 28308. There should be over 41000 lines.
Thanks,
Vahid
  3 件のコメント
Vahid Askarpour
Vahid Askarpour 2021 年 10 月 4 日
I got the script from searching Matlab Answers. The output screenshot indicates that the code works until it hits zeros.
Vahid Askarpour
Vahid Askarpour 2021 年 10 月 4 日
I did replace the %s with %5.4e and now the output is fine. The %s caused all the zeros to disappear. Thanks Walter.
Vahid

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by