for文を使ったテキストファイルの更新

7 views (last 30 days)
H.K
H.K on 2 Mar 2023
Edited: Atsushi Ueno on 2 Mar 2023
初心者です。開いたファイルにfor文を使って数字を追加しようと思うのですが、
やり方が自力でできません。
for 1:10;
F1 = max(x1(:,jj));
fileID = fopen('1.txt','w');
fprintf(fileID,'%5d\n',F1)
end
これで実行しているのですが、最後の10しか1.txtに入力されません。
1.txtに1,2,3,4・・・10まで書けるようにしたいのですが、どうすればよろしいでしょうか。
ご助言お願い致します。

Accepted Answer

Hernia Baby
Hernia Baby on 2 Mar 2023
fileIDがforループ内に入ってるからだと思います
まずは1.txtを適当に作ります
clear,clc;
a = [];
writematrix(a,'1.txt');
dir('*.txt')
1.txt
fileIDを外に出してください
x1 = randi([1 10],10);
fileID = fopen('1.txt','w');
for jj = 1:10
F1 = max(x1(:,jj));
fprintf(fileID,'%5d\n',F1);
end
fclose(fileID);
中身を確認します
type('1.txt')
10 10 9 9 10 10 10 10 10 10
  2 Comments
Hernia Baby
Hernia Baby on 2 Mar 2023
@H.Kさんが質問してくれたおかげで救われる誰かもいますので、どんどん質問してください。

Sign in to comment.

More Answers (0)

Categories

Find more on 起動と終了 in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!