Matlab数据文件的读写(2)

2020-03-26 23:03

>> A A =

8 1 6 3 5 7 4 9 2 >> B B =

0.9501 0.4860 0.4565 0.2311 0.8913 0.0185 0.6068 0.7621 0.8214 >> clear

>> open('matlab.mat') ans =

A: [3x3 double] B: [3x3 double] >> struc1=ans; >> struc1.A ans = 8 1 6 3 5 7 4 9 2 >> struc1.B

ans =

0.9501 0.4860 0.4565 0.2311 0.8913 0.0185 0.6068 0.7621 0.8214 13.2 文本文件的读写

在上一节中介绍的函数和命令主要用于读写mat文件,而在应用中,需要读写更多格式的文件,如文本文件、word文件、xml文件、xls文件、图像文件和音视频文件等。本节介绍文本文件(txt)的读写。其他文件的读写,用户可以参考MATLAB帮助文档。

MATLAB中实现文本文件读写的函数如表13-1所示。 表13-1 MATLAB中文本文件读写函数 函 数 功 能 csvread

读入以逗号分隔的数据 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

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函数在读入数据时可以指定分隔符,不指定时默认分隔符为逗号。


Matlab数据文件的读写(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:mastercam x7 64bit 破解安装说明

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: