今天帮同学写了一个程序,主要目的是从一个文件中读取数据,然后用这些数据来画图。进过短时间学习,成果如下:
matlab中的fscanf的用法如下:
A=fscanf(fid,format)
[A, count]=fscanf(fid,format,size)
[A, count]=fscanf(fid,format,size)
个人感觉用的最多的是 这样的形式:
data = fscanf(fid,format,size);
期中data为读取内容的数组,他的大小由size决定。size是一个[m n]的向量,
m为行,n为列(注意,这里读取的顺序是按列优先排列的,不明白的话可以看
下面的例子),若n取inf表示读到文件末尾。fid为fopen打开文件的返回值,
format是格式化参数(像printf、scanf)。
举个小例子:
路径+文件名:d:\moon.txt
内容:13,1,3.4
3,2.1,23
1,12,2
4,5.4,6
现在为了读取moon中的数据存在一个数组里,可以用如下方法
fid=fopen('d:\moon.txt');
data=fscanf(fid,'%f,%f,%f',[3,inf]) ;%这里得用单引号
fclose(fid);
这时data中的数据如下:
13 3 1 4
1 2.1 12 5.4
4 23 2 6
通常我们可能需要用引用数组中的某行或某列来画图,方法是data(m,:) 或者 data(:,n),即取得data数组的第m行或第n列。