how to identify values in a text file and replace them based on an existing array

2 次查看(过去 30 天)
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

采纳的回答

Ameer Hamza
Ameer Hamza 2020-10-26
编辑:Ameer Hamza 2020-10-26
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.

更多回答(1 个)

Mathieu NOE
Mathieu NOE 2020-10-26
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');

类别

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

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by