How to edit a text file using matlab?

214 次查看(过去 30 天)
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 个评论
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),',$','');

标签

Community Treasure Hunt

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

Start Hunting!

Translated by