How to add a new column in a txt file with if condition
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Bob Thompson
2019-4-17
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.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!