How to add a column to an existing file?
11 ビュー (過去 30 日間)
古いコメントを表示
Hi, I've been looking in other questions in how to add a new column to an existing file but none of the codes work or are either way too simple.
I'm attaching my test file and the column I would like to add to it.
A = [0.23;0.44;0.65;0.12];
0 件のコメント
採用された回答
A. Sawas
2019 年 4 月 5 日
I belelive you are trying to add a column of A to the file so your new file will be like this:
%--Existing file -- -- A --
4 0.45 100 0.23
3 4.54 65 0.44
2 0.23 233 0.65
1 0.45 200 0.12
Here is the code that will insert the column and save it in a new file testfile00W.txt. Assuming that the number of rows in A matches the number of rows in the file:
fidR = fopen('testfile00.txt', 'r');
fidW = fopen('testfile00W.txt', 'w');
line_ex = fgetl(fidR);
i = 1;
while line_ex > 0
fprintf(fidW,['%s\t%f' newline], line_ex, A(i));
line_ex = fgetl(fidR);
i = i + 1;
end
fclose(fidR);
fclose(fidW);
0 件のコメント
その他の回答 (1 件)
dpb
2019 年 4 月 5 日
編集済み: dpb
2019 年 4 月 5 日
Text sequential files are, well, "sequential" You can't just add in the middle by either column or line/record.
data=importdata('testfile00.txt');
dlmwrite('testfile00.txt',[data A],'\t')
Results--
>> type testfile00.txt
4 0.45 100 0.23
3 4.54 65 0.44
2 0.23 233 0.65
1 0.45 200 0.12
>>
NB: This does overwrite the existing file as your question requested. That is, of course, quite possibly very dangerous if you make any mistakes...always have backups!!! unless it is a trivial exercise to regenerate the original data.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Text Data Preparation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!