フィルターのクリア

for loop on all the lines of text

52 ビュー (過去 30 日間)
Federico Paolucci
Federico Paolucci 2022 年 10 月 29 日
編集済み: dpb 2022 年 10 月 31 日
Hello, I have the following script,
%C = readlines('TARGETOLD.txt');
C=readlines('TARGETOLD.txt');
str=char(C);
raw_data = textscan(str,'%[^\n]');
DATA=raw_data{1, 1};
Nrow=numel(DATA);
for i=1:Nrow
idx = find(contains(C,';TIME_ELAPSED:'), 1);
%A=convertStringsToChars(C(1:idx));
%writelines('_modified.txt', A);
fid = fopen('_modified.txt','w');
fprintf(fid,'%s\n',C{1:idx});
D = readlines('HeadScript.txt');
fprintf(fid,'%s\n',D);
%E = readlines('HeadScript.txt');
%fprintf(fid,'%s\n',E);
F = readlines('BottomScript.txt');
fprintf(fid,'%s\n',F);
end
in particular I would like some advice regarding the rows
for i=1:Nrow
idx = find(contains(C,';TIME_ELAPSED:'), 1);
...
end
using idx I go to recognize the string "TIME_ELAPSED" only the first time I encounter it, while I would like to recognize it several times since it appears several times in the text file. as you can see, I thought to insert a for loop on all the number of lines (Nrow) and to make idx depend on the index i, but it doesn't work!
thank you for the advice

回答 (2 件)

dpb
dpb 2022 年 10 月 29 日
編集済み: dpb 2022 年 10 月 29 日
No loop needed, at least initially...
C=readlines('TARGETOLD.txt');
idx=contains(C,';TIME_ELAPSED:');
E=C(idx);
Now, what do you want/need to do with those records?
More than likely if you would provide a sample of the input data file and explain your overall objective someone can provide a much more elegant solution than reading the file in as the string array...
  6 件のコメント
Federico
Federico 2022 年 10 月 30 日
Yes I mean that literally, there's nothing between them
dpb
dpb 2022 年 10 月 30 日
編集済み: dpb 2022 年 10 月 30 日
In that case, this is "more better" suited for a filter approach...see the new Answer for code...

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


dpb
dpb 2022 年 10 月 30 日
編集済み: dpb 2022 年 10 月 31 日
fidI=fopen('TARGETOLD.txt'); % Input file
fidO=fopen('_modified.txt','w'); % Output file
fid=fopen('HeadScript.txt'); % header file
HDR=fread(fid,'*char'); % suck up the header
fid=fclose(fid);
fid=fopen('BottomScript.txt'); % ditto for the trailer
TLR=fread(fid,'*char');
fid=fclose(fid);
% now do the work...
while ~feof(fidI)
l=fgets(fidI); % read a line
fwrite(fidO,l); % and put in output
if contains(l,';TIME_ELAPSED:') % the magic phrase
fwrite(fidO,HDR); % add the new stuff
fwrite(fidO,TLR);
end
end
fclose all
clear fid*

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by