读入以逗号分隔的数据
csvwrite
将数据写入文件,数据间以逗号分隔
dlmread
将以 ASCII 码分隔的数值数据读入到矩阵中
dlmwrite
将矩阵数据写入到文件中,以 ASCII 分隔
textread
从文本文件中读入数据,将结果分别保存
textscan
从文本文件中读入数据,将结果保存为单元数组
下面详细介绍这些函数。
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