Reading a text file with variables and parentheses between

4 次查看(过去 30 天)
Hello everyone,
I need that MATLAB read a text file in the format below, and seperate each variables with corresponding numerics, and write it back with the format of the text file again. I want to add another variable with the same number of numerical values and write it back to its initial format to be read again by my program.
species 1
species 2
species 3
(0.1
0.2
0
)
(.02
.1
.5
)
(0.1
.2
.3
)
Then, I want to add Species 4 with some numerical values in the same format as othe variables.
Thank you so much.

回答(1 个)

Walter Roberson
Walter Roberson 2023-4-5
S = fileread('YourFile.txt');
S = regexprep(S, '\)', '%g\n)');
newS = compose(S, ValuesForSpecies4);
fid = fopen('NewFile.txt', 'w');
fwrite(fid, newS);
fclose(fid);
My guess is that you will want to go slightly further and also insert the name of the 4th species. Possibly with something like
S = regexprep(S, '\(', 'name of species 4\n(', 'once');
  1 个评论
Mahdi Khademishamami
Hi Walter,
Thank you so much for the answer. I inserted your script in MATLAB, and it give me S as a character with htis output
species 1species 2species 3(0.10.20%g)(.02.1.5%g)(0.1.2.3%g)
What I want is actually identify and seperate the variables like Species 1=[0.1,0.2,0], Species2=[0.02,.1,.5], species3=[0.1,0.2,0.3], then add species4=[0,0,0] and then put it back at the same format like below
species 1
species 2
species 3
species4
(0.1
0.2
0
)
(.02
.1
.5
)
(0.1
.2
.3
)
(0
0
0
)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by