How to add a new column in a txt file with if condition

2 views (last 30 days)
I have a .txt file with 14 column. I want to add a new column (Cnew) based on values of column 5 (C5), as follows: if C5 = 0 then Cnew = -0.00999; if C5 < 0.05 then Cnew = mathematical expression f(C5); otherwise Cnew = 1. How can I obtain this?

Accepted Answer

Bob Thompson
Bob Thompson on 17 Apr 2019
What kind of data do you have in the file? The type of data really determines the complexity of this answer. The basic steps of what you're trying to do is as follows:
1) Read file information
2) Organize into array of not already done
3) Calculate new column
4) Insert column into array
5) Print data back to file
Assuming that you have only numeric data I would create a code something like this:
fid = fopen('mytxtfile.txt');
data = dmlread(fid); % With R2019a you can also use readmatrix
new = NaN(size(data,1),1);
new(data(:,5)==0) = -0.00999;
new(data(:,5)<0.05 & data(:,5) ~= 0) = f;
new(new==NaN) = 1;
data = [data(:,1:5),new,data(:,6:end)];
fclose(fid);
fid = fopen('mytxtfile.txt','w');
dlmwrite(fid,data); % With R2019a you can also use writematrix
fclose(fid);
I haven't tested this, so there might be some syntax bugs, but it should give you the idea of what you're looking to do.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!