Save Text Files in MATLAB: Step-by-Step Guide

In MATLAB, you can use the fprintf function to save data to a txt file.

For example, the following code saves a matrix to a txt file.

data = magic(5); % 创建一个5x5的魔方阵
filename = 'data.txt'; % 设置文件名

fid = fopen(filename, 'w'); % 打开文件
fprintf(fid, '%d\t%d\t%d\t%d\t%d\n', data'); % 将矩阵数据保存到文件中
fclose(fid); % 关闭文件

In the above code, a 5×5 magic square matrix called data is first created, and then a file name filename is specified for saving. Next, the file is opened using the fopen function with the write mode (‘w’). Then, the matrix data is saved to the file using the fprintf function, where ‘%d\t%d\t%d\t%d\t%d\n’ specifies the output format, and data’ transposes the matrix for correct formatting. Finally, the file is closed using the fclose function.

After running the code above, a file named data.txt will be generated in the current directory, containing the data of the magic square.

bannerAds