Save matrix to a txt file

%%Way 1(file)

1.1 save(filename,'a','-ascii')

1.2 save 路径\a.txt -ascii a

 

%%Way 2 (dlmwrite)

a=[1,2,3;5,7,9];
dlmwrite(filename,a,'delimiter','\t','precision',3,'newline','pc');

 

(注:dlmread)

 

%%Way 3 (fopen+fprintf+fclose)

dirMain = 'F:\';
fid = fopen([dirMain, 'test.txt'], 'wt');  % Create txt if the txt not exist
matrix = round(rand(4, 5) * 100);

[m, n] = size(matrix);
for i = 1 : m
     for j = 1 : n
          if j == n
          fprintf(fid, '%f\n', matrix(i,j)); % \n: new line
          else
          fprintf(fid, '%f\t', matrix(i,j)); % \t: horizontal tab
          end
     end
end
fclose(fid);

 

posted on 2020-03-14 14:26  OAREII  阅读(120)  评论(0编辑  收藏  举报

导航