Command fscanf does not read zero

Hello,
I am using a command "fscanf", but it doesn't read zero at the end of the line.
A file which I am reading contains this formatting:
1 552.45 1 1 1 0
2 870.38 1 2 2 0
name='test.txt';
fid1=fopen(name,'rt');
ab=fscanf(fid1,'%4f %5f %4f %4f %4f %4f',[1,6])
Can you help me to correct it?

1 件のコメント

Mathew Smith
Mathew Smith 2026 年 6 月 30 日 9:47
I have attached the text file. With your command I am getting this result below.
It ignores zero and reads number "2" from the second line.
1.0000 552.4500 1.0000 1.0000 1.0000 2.0000
870.3800 1.0000 2.0000 2.0000 0 0

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

回答 (2 件)

Stephen23
Stephen23 2026 年 6 月 30 日 9:42
編集済み: Stephen23 2026 年 6 月 30 日 11:22

0 投票

This looks correct to me:
fid = fopen('test.txt','rt');
mat = fscanf(fid,'%f',[6,Inf]).'
mat = 2×6
1.0000 552.4500 1.0000 1.0000 1.0000 0 2.0000 870.3800 1.0000 2.0000 2.0000 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
fclose(fid);
For comprison:
type test.txt
1 552.45 1 1 1 0 2 870.38 1 2 2 0
Walter Roberson
Walter Roberson 2026 年 6 月 30 日 17:50
移動済み: Walter Roberson 2026 年 6 月 30 日 17:51

0 投票

Your width field is not wide enough for the second field, so the trailing '5' is read as being the next field.
name = 'test.txt';
fid1 = fopen(name,'rt');
ab = fscanf(fid1,'%4f %5f %4f %4f %4f %4f',[1,6])
ab = 1×6
1.0000 552.4000 5.0000 1.0000 1.0000 1.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
frewind(fid1)
ab = fscanf(fid1,'%4f %6f %4f %4f %4f %4f',[1,6])
ab = 1×6
1.0000 552.4500 1.0000 1.0000 1.0000 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

製品

リリース

R2019b

質問済み:

2026 年 6 月 30 日 9:26

移動済み:

2026 年 6 月 30 日 17:51

Community Treasure Hunt

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

Start Hunting!

Translated by