How to add a column to an existing file?

조회 수: 25 (최근 30일)
Marisabel Gonzalez
Marisabel Gonzalez 2019년 4월 5일
편집: dpb 2019년 4월 5일
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];

채택된 답변

A. Sawas
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);

추가 답변 (1개)

dpb
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.

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by