Catalog
  1. 1. Deirectly read and write
    1. 1.1. mat file
    2. 1.2. csv,txt file
  2. 2. fopen method
  3. 3. “print” output image to file
MATLAB File Operation Summary

In doing research,We often need output the result to the file and read from the file.In this note, I will summarize the methods of reading and output method in MATLAB.

Deirectly read and write

mat file

We first consider the method of saving and read the MATLAB type file. The Matrix in MATLAB can be directly saved in a “xx.mat” file. This method can save many different result in an whole single file. I really recommend this method. This can be done as follows:

1
filename=['sweep_result_',datestr(now,'yyyy_mm_dd_HHMMSS'),'.mat'];
2
save(num2str(filename),'matrixa','matrixb','matrixc');

to read the file,

1
load('filename')

csv,txt file

the mat file can only be opened in MATLAB, In order to allow other software to open the output file. We can save the file as txt or csv file. This can be done via csvread/cavwrite, textread/textwrite,dlmwrite/dlmread,And I recommend the dlm method

1
% read csv file via "csvread"
2
data=csvread('<filename>',<begin row>,<begin column>);
3
%Write matrix M to a file, 'myFile.txt', delimited by the tab character and using a precision of 3 significant digits
4
dlmwrite('myFile.txt',M,'delimiter','\t','precision',3)
5
%Export a matrix to a file named myfile.txt. Then, append an additional matrix to the file that is offset one row below the first
6
X = magic(3);
7
dlmwrite('myfile.txt',[X*5 X/5],' ')
8
dlmwrite('myfile.txt',X,'-append', ...
9
   'roffset',1,'delimiter',' ')
10
%ead the entire file using dlmread.
11
M = dlmread('myfile.txt')

fopen method

this can be done via fopen and fprintf method

1
fid=fopen('progress.txt','at');
2
fprintf(fid,[datestr(now),' the loop step is %d \n'],lk4);
3
fclose(fid);

“print” output image to file

to save the figure in the window,the best way is to use print.

1
filename=['xxxxx_','.png'];
2
print(num2str(filename), '-dpng', '-r600')%for eps,'-deps2'
Author: Knifelee
Link: https://knifelees3.github.io/2019/04/07/A_En_MATLAB_FileOperationSummary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment