How to edit a text file using matlab?
187 ビュー (過去 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
0 件のコメント
回答 (2 件)
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
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
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),',$','');
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Text Files についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!