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

这篇MATLAB学习笔记介绍了如何保存和读取二进制.bin文件,写入txt文件,以及读取包含数字和字符的CSV文件。提到了常用函数如fopen和fprint,并提供了使用示例。

matlab学习笔记

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

注:元素按列保存

%% write and save
A = rand(3,4,'single');
fid = fopen('Asave.bin', 'wb');
fwrite(fid, A, 'single');%(句柄,变量,精度)
fclose(fid);

%% test and read
fidtest = fopen('Asave.bin', 'r');
while ~feof(fidtest)
    dataTen = fread(fidtest,'single');
end
fclose(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 -1

2. 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. ...
permissionaccess
‘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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值