MATLAB Answers

0

How to add a column to an existing file?

Asked by Marisabel Gonzalez on 5 Apr 2019
Latest activity Edited by dpb
on 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];

  0 Comments

Sign in to comment.

Products


Release

R2018a

2 Answers

Answer by A. Sawas
on 5 Apr 2019
 Accepted Answer

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 Comments

Sign in to comment.


Answer by dpb
on 5 Apr 2019
Edited by dpb
on 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.

  0 Comments

Sign in to comment.



Translated by