开发语言 学习方法 matlab读取与写入文件总结(持续更新) - %read file

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力2026 👁️ 258 次阅读

一、matlab读取与写入文件

假设现在有包含变量名为T的文件,T的维度信息有depth、time,下面进行读写操作

1、matlab读写mat文件

%read file

load D:\T.mat

%or load('D:\data\T.mat')

%%

%write file

save('T.mat','T','depth','time');%T、depth、time为保存的变量

2、matlab读写nc文件

ncdisp('D:\data\T.nc')%查看文件信息

%read file

%method 1

T = ncread('D:\data\T.nc','T');

%method 2

nc=netcdf('D:\data\T.nc');

T=nc{'T'}(:);

missval=nc{'T'}.missing_value(:);%查看变量T的缺失值;

%%

%write file

clc;clear;

%Variables to be saved

time=zeros([20,1]);

depth=zeros([15,1]);

T = zeros([15,20]);

title = 'Temperature data';

%Create a netCDF file

nw = netcdf('D:\data\T.nc', 'clobber');%'clobber':一个可选参数,表示如果文件已经存在,那么这个操作将会覆盖它.

result = redef(nw);%对NetCDF文件进行重新定义

% Create dimensions

nw('time')=length(time);

nw('depth')=length(depth); 拼多多帮助力入口

% Create variables and attributes

nw{'T'} = ncdouble('time','depth');

nw{'T'}.long_name = ncchar('Temperature');

nw{'T'}.units = ncchar('Celsius');

nw{'time'} = ncdouble('time');

nw{'time'}.long_name = ncchar('Temperature Time');

nw{'time'}.units = ncchar('days');

nw{'depth'} = ncdouble('depth');

nw{'depth'}.long_name = ncchar('Temperature Depth');

nw{'depth'}.units = ncchar('m');

result = endef(nw);

% Create global attributes

nw.title = title;

%Assign a value to a variable

nw('T')=T;

nw('time')=time;

nw('depth')=depth;

close(nw);

ncdisp('D:\data\T.nc')

3、matlab读写xlsx表格文件

%read file

T = xlsread('T.xlsx',sheet); % sheet表示工作表名称

%%

%write file

filename='T.xlsx';

xlswrite(filename,T,sheet)

4、matlab读写十进制文本文件(.txt,.data等)

T.txt文本如图所示 1870 1873 1870 -0.438 -0.336 0.177 1871 -0.273 -0.170 -0.212 1872 -0.037 0.041 -0.076 1873 0.062 -0.319 -0.404

clc;clear;

%read file

data=importdata("T.txt",' ',1);%得到data结构体,' '表示字符间间隔符号,1表示跳过第一行

T = data.data;obs_time=T(:,1);

%%

%write file

data=T; %

filename = 'T.txt'; %

fid = fopen(filename, 'w');

fprintf(fid, '%0.3f %0.3f %0.3f %0.3f \n', data'); %matlab会从列读取数据,所以data做了转秩

fclose(fid);

5、matlab遍历文件夹下的所有文件

clc;clear;

listFiles=dir(fullfile('D:\profiles\','*.nc'));

N=length(listFiles);

for i = 1:N

name=listFiles(i).name;floder = listFiles(i).folder;

ncfile = [floder,'\',name];

end

结尾:原本准备将自己常用的matlab与python读写文件的内容总结在一块,端午回家给自己放了个假,没来得及整理python的内容,留在下一次再总结,以上内容自己在学习过程中也从网上查阅了前辈的代码,在这里由衷感谢!

推荐文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧