How to add a column to an existing file?

25 Ansichten (letzte 30 Tage)
Marisabel Gonzalez
Marisabel Gonzalez am 5 Apr. 2019
Bearbeitet: dpb am 5 Apr. 2019
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];

Akzeptierte Antwort

A. Sawas
A. Sawas am 5 Apr. 2019
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);

Weitere Antworten (1)

dpb
dpb am 5 Apr. 2019
Bearbeitet: dpb am 5 Apr. 2019
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.

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by