フィルターのクリア

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

1 回表示 (過去 30 日間)
Livia Servanzi
Livia Servanzi 2019 年 4 月 17 日
回答済み: Bob Thompson 2019 年 4 月 17 日
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?

採用された回答

Bob Thompson
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 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by