How to edit a text file using matlab?

214 vues (au cours des 30 derniers jours)
imed NASRI
imed NASRI le 19 Mar 2014
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

Réponses (2)

David Sanchez
David Sanchez le 19 Mar 2014
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 commentaires
imed NASRI
imed NASRI le 19 Mar 2014
Thank you very much
Thuan
Thuan le 11 Nov 2017
IGNORE this comment I just want to have a way to save this in my account as I like the code.

Connectez-vous pour commenter.


Akira Agata
Akira Agata le 12 Nov 2017
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