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