How to edit a text file using matlab?

조회 수: 214 (최근 30일)
imed NASRI
imed NASRI 2014년 3월 19일
답변: Akira Agata 2017년 11월 12일
Hello,
I have a text file that is in the following form:
1 1 4 0 6
1 2 9 5 6
I want to add braces and semicolons on all lines of the file to have the following form:
{1,1,4,0,6},
{1,2,9,5,6}
I am looking for a matlab function that does this automatically without having to change my file manually because the original file contains 200 lines. thank you

답변 (2개)

David Sanchez
David Sanchez 2014년 3월 19일
fid =fopen('your_file.txt');
C=textscan(fid,'%s','delimiter','\n');
fclose(fid);
for k=1:numel(C{1,1})
tmp = regexp(C{1,1}(k),'\s'); % find empty spaces
C{1,1}{k,1}(tmp{1,1}) = ','; % substitute empty spaces by ','
C{1,1}(k) = strcat('{',C{1,1}(k),'},'); % add brackets
end
% print new file
fName = 'new_file.txt';
fid = fopen(fName,'w'); % Open the file
for k=1:numel(C{1,1})
fprintf(fid,'%s\r\n',C{1,1}{k,1});
end
fclose(fid);
  댓글 수: 2
imed NASRI
imed NASRI 2014년 3월 19일
Thank you very much
Thuan
Thuan 2017년 11월 11일
IGNORE this comment I just want to have a way to save this in my account as I like the code.

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


Akira Agata
Akira Agata 2017년 11월 12일
Here is an another way to do that without using for-loop.
% After textscan
C = {'1 1 4 0 6';'1 2 9 5 6'};
% Replace space with ','
C = regexprep(C,'\s',',');
% Add '{' and '},' for each line
C = cellfun(@(x) ['{',x,'},'],C,'UniformOutput',false);
% Delete the last ',' at the last line
C(end) = regexprep(C(end),',$','');

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by