How to edit a text file using matlab?

210 ビュー (過去 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 Center および File ExchangeText Files についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by