how to identify values in a text file and replace them based on an existing array
4 views (last 30 days)
Show older comments
Hello,
I have a text file, let's call it abc.txt, such as that I am writing below. I would like to replace the values that are after '=' of each line that starts in ARF
Example:
ARF1=0.4
ARF2=0.6
ARF3=0.7
ARF4=0.8
ARF5=0.7
ARF6=0.6
ARF7=0.4
asd
asd
gh
wer
asd
qwe
asd
with the values of an existing array:
B=[3;5;4;6;5;3;8]
so the resultant text file would be:
ARF1=3
ARF2=5
ARF3=4
ARF4=6
ARF5=5
ARF6=3
ARF7=8
asd
asd
gh
wer
asd
qwe
asd
How could I do it?
I am using MATLAB R2018b.
Best regards,
Hugo
1 Comment
Accepted Answer
Ameer Hamza
on 26 Oct 2020
Edited: Ameer Hamza
on 26 Oct 2020
This is one of the way
B=[3;5;4;6;5;3;8];
fid = fopen('data.txt');
data1 = textscan(fid, 'ARF%f=%f');
data2 = textscan(fid, '%s');
fclose(fid);
data1_new = compose('ARF%d=%.0f', data1{1}, B);
data_new = [data1_new; data2{1}];
fid = fopen('data_new.txt', 'w');
fprintf(fid, '%s\n', data_new{:});
fclose(fid);
data.txt is attached.
0 Comments
More Answers (1)
Mathieu NOE
on 26 Oct 2020
hello
this is a way to do it
T = readtable('data.txt');
% T =
%
% 14×2 table
%
% Var1 Var2
% ________ ____
%
% {'ARF1'} 0.4
% {'ARF2'} 0.6
% {'ARF3'} 0.7
% {'ARF4'} 0.8
% {'ARF5'} 0.7
% {'ARF6'} 0.6
% {'ARF7'} 0.4
% {'asd' } NaN
% {'asd' } NaN
% {'gh' } NaN
% {'wer' } NaN
% {'asd' } NaN
% {'qwe' } NaN
% {'asd' } NaN
% conversion table to cell array
TC = table2cell(T);
TC_out = TC; % initialization (out put table = input table)
% new data
B=[3;5;4;6;5;3;8];
[m,n] = size(TC);
p = 0;
for ci = 1:m
if findstr(TC{ci},'ARF')
p = p+1;
TC_out{p,2} = B(p);
end
end
% save TC_out to table
writecell(TC_out,'data_out.txt');
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!