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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Ameer Hamza
Ameer Hamza il 26 Ott 2020
Modificato: Ameer Hamza il 26 Ott 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.

Più risposte (1)

Mathieu NOE
Mathieu NOE il 26 Ott 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');

Categorie

Scopri di più su Data Import and Analysis in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by