matlab读寫文件--bin/txt/csv

来源:互联网 发布:淘宝长尾词怎么找 编辑:程序博客网 时间:2024/06/07 13:32

matlab学习笔记

保存和读取二进制文件.bin

注:元素按列保存

%% write and saveA = rand(3,4,'single');fid = fopen('Asave.bin', 'wb');fwrite(fid, A, 'single');%(句柄,变量,精度)fclose(fid);%% test and readfidtest = fopen('Asave.bin', 'r');while ~feof(fidtest)    dataTen = fread(fidtest,'single');endfclose(fidtest);

以上保存的是很簡單的數據,在實際應用時會發現會有不同的需求。在這裏只是簡單的記錄下平常用到的功能,比較片面,還是matlab doc大法好,多查多看。

寫入txt文件

x = 0:.1:1;A = [x; exp(x)];fileID = fopen('exp.txt','w');fprintf(fileID,'%6s %12s\n','x','exp(x)');fprintf(fileID,'%6.2f %12.8f\n',A);fclose(fileID);

讀取包含數字和字符的CSV文件

reference:http://www.ilovematlab.cn/thread-115241-1-1.html

%本文件用于含表头的csv文件读取,数据返回格式为cell类型和int32数据类型clear;close all;%打开csv文件fid = fopen('20101231.csv');%读取表头 数据返回为cell类型 调用格式title{1}title = textscan(fid, '%s %s %s %s %s %s %s %s %s %s',1,'delimiter', ',')%读取数据 返回为cell类型data = textscan(fid, '%s %d32 %d32 %d32 %d32 %d32 %d32 %d32 %d32 %d32','delimiter', ',')fclose(fid);

常用函數及參數說明

fopen — Open file, or obtain information about open files

1.fileID = fopen(filename)     % returns an integer file identifier equal to or greater than 3  % If fopen cannot open the file, then fileID is -12. fileID = fopen(filename,permission)  % permission means file access type, such as 'r'(default), 'w+', 'a+', 'A', 'W' and so on .  % 後面幾個不怎麼用到3. fileID = fopen(filename,permission,machinefmt,encodingIn)4. [fileID,errmsg] = fopen(___)5. fIDs = fopen('all')6. ...
permission access ‘r’ Open file for reading ‘w’ Open or create new file for writing. Discard existing contents, if any. ‘a’ Open or create new file for writing. Append data to the end of the file. ‘r+’ Open file for reading and writing. ‘w+’ Open or create new file for reading and writing.Discard existing contents, if any. ‘a+’ Open or create new file for reading and writing. Append data to the end of the file. ‘A’ Append without automatic flushing of the current output buffer. ‘W’ Write without automatic flushing of the current output buffer.

fprint — Write data to text file

1.fprintf(fileID,formatSpec,A1,...,An)2.fprintf(formatSpec,A1,...,An)  % Print multiple numeric values and literal text to the screen.

example:

A1 = [9.9, 9900];A2 = [8.8,  7.7 ; ...      8800, 7700];formatSpec = 'X is %4.2f meters or %8.3f mm\n';fprintf(formatSpec,A1,A2)

screen will display:
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm

0 0
原创粉丝点击