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

2 ビュー (過去 30 日間)
Hugo
Hugo 2020 年 10 月 26 日
回答済み: Mathieu NOE 2020 年 10 月 26 日
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 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 26 日
fileread(), do some careful regexprep(), write out to a new file.

サインインしてコメントする。

採用された回答

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 Center および File ExchangeData Import and Analysis についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by