下面详细介绍这些函数。
1. csvread、csvwrite
csvread函数的调用格式如下:
● M = csvread('filename'),将文件filename中的数据读入,并且保存为M,filename中只能包含数字,并且数字之间以逗号分隔。M是一个数组,行数与filename的行数相同,列数为filename列的最大值,对于元素不足的行,以0补充。
● M = csvread('filename', row, col),读取文件filename中的数据,起始行为row,起始列为col,需要注意的是,此时的行列从0开始。
● M = csvread('filename', row, col, range),读取文件filename 中的数据,起始行为 row,起始列为col,读取的数据由数组 range 指定,range 的格式为:[R1 C1 R2 C2],其中R1、C1为读取区域左上角的行和列,R2、C2为读取区域右下角的行和列。
csvwrite 函数的调用格式如下:
● csvwrite('filename',M),将数组M中的数据保存为文件filename,数据间以逗号分隔。
● csvwrite('filename',M,row,col),将数组M中的指定数据保存在文件中,数据由参数 row和col指定,保存row和col右下角的数据。
● csvwrite写入数据时每一行以换行符结束。另外,该函数不返回任何值。
这两个函数的应用见下面的例子。
例13-4 函数csvread和csvwrite 的应用。
本例首先将MATLAB的图标转化为灰度图,将数据存储在文本文件中,再将其部分读出,显示为图形。
编写M文件,命名为immatlab.m,内容为:
% the example of functions csvread and csvwrite
I_MATLAB= imread('D:\matlab.bmp'); % read in the image
I_MATLAB= rgb2gray(I_matlab); % convert the image to gray image
figure,imshow(I_matlab,'InitialMagnification',100); % show the image
csvwrite('D:\matlab.txt',I_matlab); % write the data into a text file
sub_MATLAB= csvread('D:\matlab.txt',100,100);% read in part of the data
sub_MATLAB= uint8(sub_matlab); % convert the data to uint8
figure,imshow(sub_matlab,'InitialMagnification',100); % show the new image
在命令窗口中运行该脚本,输出图形如图13-2所示。
(a) (b)
图13-2 例13-3 的运行结果
该例中涉及到了少量的图像处理内容,超出本书的范围,感兴趣的读者可以查阅 MATLAB帮助文档中关于Image Processing Toolbox的介绍。
2. dlmread、dlmwrite(个人觉得这个比较好用)
dlmread函数用于从文档中读入数据,其功能强于csvread。dlmread的调用格式如下:
● M = dlmread('filename')
● M = dlmread('filename', delimiter)
● M = dlmread('filename', delimiter, R, C)
● M = dlmread('filename', delimiter, range)
其中参数delimiter用于指定文件中的分隔符,其他参数的意义与csvread函数中参数的意义相同,这里不再赘述。dlmread函数与csvread函数的差别在于,dlmread函数在读入数据时可以指定分隔符,不指定时默认分隔符为逗号。
dlmwrite函数用于向文档中写入数据,其功能强于csvwrite函数。dlmwrite函数的调用格式为:
● dlmwrite('filename', M),将矩阵M的数据写入文件filename中,以逗号分隔。
● dlmwrite('filename', M, 'D'),将矩阵M的数据写入文件filename中,采用指定的分隔符分隔数据,如果需要tab键,可以用“\t”指定。
● dlmwrite('filename', M, 'D', R, C),指定写入数据的起始位置。
● dlmwrite('filename', M, attribute1, value1, attribute2, value2, ...),指定任意数目的参数,可以指定的参数见下表。
● dlmwrite('filename', M, '-append'),如果filename指定的文件存在,在文件后面写入数据,不指定时则覆盖原文件。
● dlmwrite('filename', M, '-append', attribute-value list),叙写文件,并指定参数。
● dlmwrite 函数的可用参数如表13-2所示。