




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、2020/6/23,第四章 文件操作 Chapter Four: File Operations,MATLAB 语 言 MATLAB Language,2020/6/23,In Matlab environment, There are two type files as following: 1. Program file or M-file General program and function program. 2. Data file The system not only provide general function of file management, but also g
2、ives a lot of special function for file operation. MATLAB 环境下的文件与其它系统一样,也有两类文件组成,一类是程序文件,又称M文件,另一类是数据文件。系统除提供了文件的一般管理功能外,还提供了对数据文件进行操作的特殊功能函数。,2020/6/23,4.1 基本命令 (Basic command),1. Help command HELP Display help text in Command Window. Form: help Example: help plot help matlabgeneral 2. What command
3、 WHAT List Matlab-specific files in directory. Form: what Example: what matlab List all the M-files of matlab directory.,2020/6/23,3. Type commamd TYPE List M-file. type foo.bar %lists the ascii file called foo.bar. type foo %lists the ascii file called foo.m. Form: type 4. Lookfor command Form: loo
4、kfor 寻找命令或字符串是否存在。 Example: lookfor cos,4.1 基本命令 (Basic command),2020/6/23,5which command of function search which item displays the full path for item. 显示item所在的全路径。 str = which(item) returns the full path for item in the string, str. 将item的全路径返回到变量str。 Example: which pinv, str = which(pinv); 6 pat
5、h command of control path PATH view or change search path. 查看或改变搜索路径。 path displays the Matlab search path, which is stored in pathdef.m. 显示Matlab搜索路径,储存在pathdef.m中。 path(newpath) changes the search path to newpath, where newpath is a string array of folders. 将当前搜索路径设置为newpath。,4.1 基本命令 (Basic comma
6、nd),2020/6/23,6 path command of control path path(path,newpath) adds the newpath folder to the end of the search path. If newpath is already on the search path, then path(path, newpath) moves newpath to the end of the search path. (将newpath添加到搜索路径之尾) path(newpath,path) adds the newpath folder to the
7、 top of the search path. If newpath is already on the search path, then path(newpath, path) moves newpath to the top of the search path. To add multiple folders in one statement, instead use addpath. (将newpath添加到搜索路径之首) p = path returns the search path to string variable p. Example: path( c:toolsgoo
8、dstuff),4.1 基本命令 (Basic command),2020/6/23,7who, whos 显示变量命令 WHO list current variables. (Only name) WHOS list current variables as a long form of WHO. (Including Name, Size, Bytes and Class) 8 load, save 装载,保存workspace命令 load filename or load(filename) loads all variables from the MAT-file, filenam
9、e into workspace. load filename variables or load(filename,variables) loads the specified variables from the MAT-file, filename. load filename -ascii or load(filename,-ascii) treats filename as an ASCII file, regardless of the file extension.,4.1 基本命令 (Basic command),2020/6/23,save filename or save(
10、filename) saves all variables from the current workspace in a Matlab formatted binary file (MAT-file) called filename. If filename already exists, save overwrites the file. save test or save(test) or save(test.mat) Saves all variables of workspace to file test.mat. save test x y Only save x, y to fi
11、le test.mat. save pqfile.txt x y -ascii or save(pqfile.txt,x,y,-ascii) Uses 8-digit ascii form instead of binary regardless of file extension. save . -ascii double Uses 16-digit ASCII form. save . append Adds the variables to an existing file (MAT-file only).,4.1 基本命令 (Basic command),2020/6/23,9 cle
12、ar 清除变量命令 clear removes all variables from the current workspace, releasing them from system memory. Example: clear % Removes all variables from the workspace. clear x y % Clear x, y clear a* % Clear variables starting with a 10 disp 显示文本或变量内容 disp(X) displays the array, without printing the array n
13、ame. If X is a string, the text is displayed. Example: x=1 2 3 disp(x) y=I love you. disp(y),4.1 基本命令 (Basic command),2020/6/23,11 cd 改变目录命令 CD, by itself, prints out the current directory. CD directory-spec sets the current directory to directory-spe. CD . moves to the directory above the current o
14、ne. WD = CD returns the current directory as a string. 12 dir 显示目录内容命令 DIR list directory. 显示目录里的文件。 Example: dir C:Program Files cd(C:Program Files) D=dir(C:Program Files),4.1 基本命令 (Basic command),2020/6/23,13Delete command Delete command deletes file or graphics object. 删除文件或对象命令。 delete file_name
15、 deletes the named file from disk. Form: delete %可以使用通配符*,? delete Example1: H=plot(X, X) % 建立图形对象H delete(H) % 删除图形对象H Example2: delete *.p % deletes all P-files from the current directory.,4.1 基本命令 (Basic command),2020/6/23,4.2 高级文件的输入输出,File import/export functions. dlmwrite - Write ASCII delimit
16、ed file. dlmread - Read ASCII delimited file. xlsread - Read Microsoft Excel spreadsheet file. xlswrite -Write to Microsoft Excel spreadsheet file. importdata - Load data from file. load - Load data from MAT-file into workspace. save - Save workspace variables to file.,2020/6/23,DLMWRITE 写ASCII分隔的文件
17、,dlmwrite(filename, M, DLM) 将矩阵 M写入文件filename,用DLM作为分隔符。指定 t产生tab-分隔(4个空格)的文件。 dlmwrite(filename, M, DLM, R, C) 从文件filename中偏移R行,C列开始将矩阵 M写入,用DLM作为分隔符。 R和C都基于零(0)的,所以 R=C=0指文件中第一数据。,4.2 高级文件的输入输出,2020/6/23,DLMREAD 读ASCII分隔的文件,result= dlmread(filename, delimiter) 从分隔符为delimiter的文件filename中读取数值数据,结果由
18、RESULT返回.用 t表示tab. result = dlmread(filename, delimiter, R, C) 从delimiter分隔的文件filename中读取数据。 R 和C指明文件中数据的左上角 R行和 C列。 R和C都基于零(0)的,所以 R=0和C=0指文件中第一数据。 result = dlmread(filename, delimiter, range) 在由range = R1 C1 R2 C2指定的范围内读,其中 (R1,C1) 为要读的数据的左上角, (R2,C2)为右下角。range 也可以用表单符号(spreadsheet notation )指定,例如
19、range = A1.B7。 dlmread用零填充空分隔域。用非空白分隔符作为行结束的数据文件,将产生带零填充的额外的最后列的结果 。举例 M = dlmread(count.dat,0,0),4.2 高级文件的输入输出,2020/6/23,XLSREAD 读 Excel电子表格 (XLS)文件,A = xlsread(filename) 返回Microsoft Excel文件filename中的第一表单中的数值数据 A, B = xlsread(filename) 数值数据存入A中,文本数据存入 B. . = xlsread(filename,sheetname) a,b=xlsread(
20、c:book1.xls,程述汉) 与上相同,但用表单名sheetname. 若表单sheetname不存在,则为一错误。 空单元格(Empty cells) ,或具有文本的单元格在数值结果中产生NaN。 文本打头行(Leading rows and columns of text)不在数值结果中产生NaN。 这使得装载这样的文件很方便。,4.2 高级文件的输入输出,2020/6/23,XLSREAD 读 Excel电子表格 (XLS)文件,为从文件中获得有用的表单名,调用具有两个输出的xlsfino函数,如: status, sheetnames = xlsfinfo(filename) 当从
21、Excel文件中读取日期域时,日期数据必须转换为MATLAB日期。如,若在Excel文件中包含: 4/12/99 4/13/99 4/14/99 象这样把数据转换为 MATLAB日期: excelDates = xlsread(filename) matlabDates = datenum(30-Dec-1899) + excelDates,4.2 高级文件的输入输出,2020/6/23,Calling format: xlswrite(filename,A) xlswrite(filename,A,sheet) xlswrite(filename,A,xlRange) xlswrite(fi
22、lename,A,sheet,xlRange) Examples: % Write a 7-element vector to testdata.xls: xlswrite(testdata.xls, 12.7, 5.02, -98, 63.9, 0, -.2, 56) % Write mixed text and numeric data to testdata2.xls % starting at cell E1 of Sheet1: d = Time,Temperature; 12,98; 13,99; 14,97; xlswrite(testdata2.xls, d, 1, E1),4
23、.2 高级文件的输入输出,xlswrite 写数据到 Excel电子表格 (XLS)文件,2020/6/23,Calling format: A = importdata(filename) A = importdata(-pastespecial) A = importdata(_,delimiterIn) A = importdata(_,delimiterIn,headerlinesIn) A,delimiterOut,headerlinesOut = importdata(_) Examples: Import and Display an Image. %Import and dis
24、play the sample image, ngc6543a.jpg. A = importdata(ngc6543a.jpg); image(A),4.2 高级文件的输入输出,importdata 从文件中装载数据,2020/6/23,Examples: Import a Text File and Specify Delimiter and Column Header. Using a text editor, create a space-delimited ASCII file with column headers called myfile01.txt. Day1 Day2 Da
25、y3 Day4 Day5 Day6 Day7 95.01 76.21 61.54 40.57 5.79 20.28 1.53 23.11 45.65 79.19 93.55 35.29 19.87 74.68 60.68 1.85 92.18 91.69 81.32 60.38 44.51 48.60 82.14 73.82 41.03 0.99 27.22 93.18 89.13 44.47 17.63 89.36 13.89 19.88 46.60 Import the file, specifying the space delimiter and the single column h
26、eader. filename = myfile01.txt; delimiterIn = ; headerlinesIn = 1; A = importdata(filename,delimiterIn,headerlinesIn);,4.2 高级文件的输入输出,importdata 从文件中装载数据,2020/6/23,Examples: Import a Text File and Return Detected Delimiter Using a text editor, create a comma-delimited ASCII file called myfile02.txt.
27、1,2,3 4,5,6 7,8,9 Import the file, and display the output data and detected delimiter character. filename = myfile02.txt; A,delimiterOut=importdata(filename),4.2 高级文件的输入输出,importdata 从文件中装载数据,2020/6/23,4.3 文件的打开与关闭,Matlab提供了对数据文件建立、打开、读、写以及关闭等一系列函数,数据文件一般存放在磁盘等介质上,用文件名标识,系统对文件名没有特殊要求。数据文件的格式有二种形式,一是
28、二进制格式文件,二是ASCII文本文件,系统对这两类文件提供了不同的读写功能函数。,2020/6/23,4.3 文件的打开与关闭,. Fopen function FOPEN open file. 打开文件。 FID = fopen(Filename) opens the file Filename for read access. (On PC systems, fopen opens files for binary read access.) FID is a scalar MATLAB integer, called a file identifier. If FOPEN cannot
29、 open the file, it returns -1. FID= fopen(Filename, Permission) opens the file Filename in the mode specified by Permission. FID, MESSAGE = fopen(Filename, Permission) returns a system dependent error message if the open is not successful.,2020/6/23,4.3 文件的打开与关闭,The Permission can be: r read w write
30、 (create if necessary) a append (create if necessary) r+ read and write (do not create) w+ truncate or create for read and write 为读/写建立一个新的文本文件 a+ read and append (create if necessary) W write without automatic flushing写但不自动覆盖 A append without automatic flushing 追加数据但不自动覆盖,2020/6/23,4.3 文件的打开与关闭,Suc
31、h as, to open the data file std.dat for reading, we can use following command: FID=fopen(std.dat, r) Files can be opened in binary mode (the default) or in text mode. To open in text mode, add t to the permission string, for example rt and wt+. 打开文件的默认格式为二进制格式,如果想用ASCII文本格式,须在格式字符串中加上字符t,例如用rt表示以ASC
32、II格式打开供读操作的数据文件。,2020/6/23,4.3 文件的打开与关闭,2 fclose关闭文件 ST = fclose(FID) closes the file with file identifier FID, which is an integer obtained from an earlier FOPEN. FCLOSE returns 0 if successful and -1 if not. 文件在进行完读、写等操作后,应及时关闭,以保证文件的安全可靠。关闭文件命令格式为: ST=fclose(FID) %关闭FID所表示的文件 其中ST表示关闭文件操作的返回代码,若关
33、闭成功,返回0,否则返回1。,2020/6/23,二进制数据文件 A = fread(FID) reads binary data from the specified file and writes it into matrix A. FID is an integer file identifier obtained from fopen. A = fread(FID, sizeA) reads the number of elements specified by SIZE. Valid entries for sizeA are: N read N elements into a co
34、lumn vector. inf read to the end of the file. M,N read elements to fill an M-by-N matrix, in column order. N can be inf, but M cant. A = fread(FID,sizeA,precision) reads the file according to the data format specified by the string precision. A,COUNT=fread() optional output argument COUNT returns th
35、e number of elements successfully read.,4.4 文件的读写操作,2020/6/23,Any of the following strings, either the MATLAB version, or their C or Fortran equivalent, may be used. If not specified, the default precision is uchar. MATLAB C or Fortran Description uchar unsigned char unsigned character, 8 bits. scha
36、r signed char signed character, 8 bits. int8 integer*1 integer, 8 bits. int16 integer*2 integer, 16 bits. int32 integer*4 integer, 32 bits. int64 integer*8 integer, 64 bits. uint8 integer*1 unsigned integer, 8 bits.无符号整数 uint16 integer*2 unsigned integer, 16 bits. uint32 integer*4 unsigned integer,
37、32 bits. uint64 integer*8 unsigned integer, 64 bits. single real*4 floating point, 32 bits. float32 real*4 floating point, 32 bits. double real*8 floating point, 64 bits. float64 real*8 floating point, 64 bits.,4.4 文件的读写操作,2020/6/23,short, long, ushort, ulong, integer*4(1,2,4,8), real*4(4,8) 等也是有效的p
38、recision。 Example: FID=fopen(std.dat, r); A=fread(FID, 100, long); Sta=fclose(FID); 以读数据方式打开数据文件std.dat,并按长整型数据格式读取文件的前100个数据放入向量A,然后关闭文件。,4.4 文件的读写操作,2020/6/23,Fwrite function write binary data to file. COUNT = fwrite(FID,A,Precision) writes the elements of matrix A to the specified file, translati
39、ng MATLAB values to the specified precision. The data are written in column order. COUNT is the number of elements successfully written. Precision controls the form and size of the result. See the list of allowed precisions under Fread. Example: FID=fopen(magic5.bin, w+); fwrite(FID, magic,int32);,4
40、.4 文件的读写操作,2020/6/23,【例1】建立一数据文件test.dat,用于存放矩阵A的数据。 已知A=-0.6515 -0.2727 -0.4354 -0.3190 -0.9047 -0.7534 -0.4567 -0.3212 -0.4132 -0.3583 -0.9264 -0.8173 -0.7823 -0.3265 -0.0631 -0.1735 -0.7373 -0.0972 -0.3267 -0.6298 -0.4768 -0.6773 -0.6574 -0.1923 -0.4389,4.4 文件的读写操作,2020/6/23,下述程序段将矩阵A的数据以二进制浮点数格式
41、写入文件test.dat中。 Fid=fopen(test.dat, w) cnt=fwrite(Fid, A, float) fclose(Fid) 下述程序读取文件test.dat的内容。 Fid=fopen(test.dat, r) B,cnt=fread(Fid,5,inf, float) fclose(Fid),4.4 文件的读写操作,2020/6/23,2. 文本文件 Fscanf read formatted data from file. 读ASCII文本文件。 A = fscanf(fileID,formatSpec) reads data from an open text
42、 file into column vector A and interprets values in the file according to the format specified by formatSpec. The fscanf function reapplies the format throughout the entire file and positions the file pointer at the end-of-file marker. If fscanf cannot match formatSpec to the data, it reads only the
43、 portion that matches and stops processing. 按formatSpec指定的格式读取文本文件fileID的全部数据到列向量A,数据和解释价值的文件按指定格式的formatspec。fscanf函数重复的格式,使文件指针指向文件结尾标记。如果数据与formatspec不匹配, fscanf只读取部分匹配的并停止处理。,4.4 文件的读写操作,2020/6/23,2. 文本文件 formatSpec is a string containing C language conversion specifications. Conversion specific
44、ations involve the character %, optional assignment-suppressing asterisk and width field, and a conversion characters (such as d, i, o, u, x, e, f, g, s, or c). Example: formatSpec is %*d %s,4.4 文件的读写操作,2020/6/23,2. 文本文件 formatSpec用来控制读取的数据格式,由% 加上格式符组成,常用格式如下: %d -十进制有符号整数 %5d读一个多达 5 位的有符号整数或直到下一分隔
45、符 %u -十进制无符号整数(类似于%d) %o -八进制无符号整数 %x -十六进制无符号整数 %f - Floating-point fields can contain any of the following (not case sensitive): Inf, -Inf, NaN, or -NaN. %5f - reads up to 5 digits or until next delimiter %e -浮点数(科学计数法) %g 浮点数(自动),4.4 文件的读写操作,2020/6/23,2. 文本文件 %s - Read a string until fscanf encou
46、nters white space %5s - reads up to 5 characters or until white space %c - Read any single character, including white space. To read multiple characters at a time, specify field width. %5c - reads up to 5 characters including whitespace %i Signed integer, base 10 or base 8 or base 16, according to t
47、he values in the file,4.4 文件的读写操作,2020/6/23,2. 文本文件 A = fscanf(fileID,formatSpec,sizeA) reads file data into an array, A, with dimensions, sizeA, and positions the file pointer after the last value read. fscanf populates A in column order. sizeA=n读取n个数据到一个列向量;sizeA=n,m读取mn个数据到一个mn矩阵中,按列存放;sizeA=INF读
48、取整个文件。 A,count = fscanf(_) additionally returns the number of fields that fscanf reads into A. For numeric data, this is the number of values read. You can use this syntax with any of the input arguments of the previous syntaxes. Count为成功读取到A中的数据个数。,4.4 文件的读写操作,2020/6/23,举例: FID = fopen(count.dat);
49、S = fscanf(FID,%s) %Read (and returns) a character string, no white space. S为一个无空格的字符串 frewind(FID); %回绕到文件头部 D = fscanf(FID,%5d) %Read 5-digit decimal integers. D为一个仅有1列的列数组 frewind(FID); F= fscanf(FID, %f) %Use the string, %f, to specify floating-point. 举例: fid = fopen(count.dat); A = fscanf(fid,%
50、d,6,inf); %设定A为6列,已转置 fclose(fid);,4.4 文件的读写操作,2020/6/23,4.4 文件的读写操作,fprintf 函数写ASCII数据文件,其格式为: nbytes= fprintf(FID,formatSpec, A,) 其中A为要写入文件的数据矩阵,先按formatSpec格式化数据矩阵A,后写入到Fid所指定的文件。nbytes为写入数量。 fprintf(FID,formatSpec,A1,.,An) 写入多个矩阵。 举例: x = 0:.1:1; A = x; exp(x); fileID = fopen(exp.txt,w); fprintf
51、(fileID,%6s %12sn,x,exp(x); fprintf(fileID,%6.2f %12.8fn,A); fclose(fileID);,2020/6/23,fgetl 和 fgets fgetl和fgets命令都是用来读取文件的下一行,两者的差别是fgetl会舍去换行符,而fgets则保留换行符。语法如下: tline=fgetl(FID) %读取文件的下一行,不包括换行符 tline=fgets(FID) %读取文件的下一行,包括换行符 tline=fgets(FID,nchar) %限制读取文件字符个数 说明:FID为文件标识号(ID);tline为以字符串形式的返回值,
52、如果到文件末尾则返回-1;nchar为最多返回的字符个数。请看下列例子:,4.4 文件的读写操作,2020/6/23,程序 1: fid = fopen(exp.txt, r); for i=1:11 tline=fgetl(fid); n=length(tline); A(i,1:n)=tline; end; fclose(fid) 程序 2: fid = fopen(exp.txt, r); i=0; while feof(fid) i=i+1; tline=fgetl(fid); n=length(tline); A(i,1:n)=tline; end; fclose(fid),4.4
53、文件的读写操作,2020/6/23,程序3: fid=fopen(exp.txt,r) ; %打开exp.txt文件只读 fgetl(fid) %读取第一行数据 fgets(fid) %读取第二行数据 fgets(fid,10) %读取第三行数据,限制10个字符 fgets(fid,10) %继续读取第三行数据,限制10个字符 fgets(fid) %读取第三行剩余的数据 fgets(fid) %读取第四行数据 fclose(fid) ) %关闭exp.txt,4.4 文件的读写操作,2020/6/23,4.5 数据文件定位写操作,1. fseek函数 Fseek set file position indicator. STATUS = fseek(FID, OFFSET, ORIGIN) repositions the file position indicator in the file with the given FID to the byte with the specified OFFSET relative to ORIGIN. OFFSET values are interpret
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 运营企业薪酬管理办法
- 进口小麦溯源管理办法
- 进口鸡爪销毁管理办法
- 远程视频督查管理办法
- 违规退赔资金管理办法
- 退休军人优待管理办法
- 邮政区域承包结算管理办法
- 郑州小学生餐饮管理办法
- 鄞州区绿色岗亭管理办法
- 银监会投资业务管理办法
- 学堂在线 大学生国家安全教育 期末考试答案
- 碳化硅培训课件
- 2025年三门峡卢氏县事业单位(联考)招聘81人笔试模拟试题及答案
- 2025年公需科目考试试卷(含答案)
- 暑假教研活动方案
- 2025年广西中考物理试题及答案
- 车辆事故警示教育
- 2024年北京市海淀区招聘社区工作者考试真题
- 2025年广东中考数学试题(含答案详解)
- 2025年 四川省港航投资集团有限责任公司招聘考试笔试试卷附答案
- 干眼的药物治疗讲课件
评论
0/150
提交评论