How to replace part of string of cell array inside for loop

조회 수: 1 (최근 30일)
Danupon Subanapong
Danupon Subanapong 2018년 11월 16일
댓글: Danupon Subanapong 2018년 11월 17일
Hi!! I would like to ask for some help. I am now importing a number of input data. I attacheh some examples of input files. Please refer to them. Some file contains some missing data. I would like to replace the missing data by some value. I have coded as below.
for j=1:5
File_name_i(j,1)=string(sprintf('%s%u%s','File',j,'.txt');
fid(j,1)=fopen(File_name_i(j,1));
f(j,1)=textscan(fid(j,1),'%s', 'delimiter','\n');
fclose(fid(j,1));
Data{j}=regexprep(f{j,1},'**********','0000.00'); %% ********** is one form of missing data and I want to replace these missing data by 0
Data{j}=regexprep(f{j,1},'NaN','0000.00'); %% NaN is another form of missing data and I want to replace these missing data by 0
Data1{j,1}=Data{j}(4:end,:);
end
Later, I will convert this cell array (Data1) to array.
However, the code above doesn't work. I have tried to it regexprep individually (without loop) and it works. So, I think the problem is to use regexprep inside for loop.
Could you please give me some suggestion or solution to this problem?
Thank you in advance
  댓글 수: 1
Adam Danz
Adam Danz 2018년 11월 16일
What do mean "it doesn't work"? I tested it on the first file and it works fine. If you're getting an error, share the entire error message and point to which line is causing it. If you're getting unexpected results describe the results you expect to get and how they differ from the results you're getting.

댓글을 달려면 로그인하십시오.

채택된 답변

per isakson
per isakson 2018년 11월 16일
편집: per isakson 2018년 11월 16일
A slightly different approach
%%
File_name_i = string.empty(5,0);
for j=1:5
File_name_i(j,1)=string(sprintf('%s%u%s','File',j,'.txt'));
str = fileread( File_name_i(j,1) );
%
% ********** is one form of missing data and I want to replace these missing data by 0
% NaN is another form of missing data and I want to replace these missing data by 0
str = strrep( str, '**********', '0.0' );
str = strrep( str, 'NaN', '0.0' );
Data(j,1) = textscan( str,'%f%f%f%f%f', 'Delimiter',' ', 'CollectOutput',true );
end
"regexprep inside for loop" shouldn't be a problem, however, it's a bit of over-kill.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by