Matlab中导入文件的命令大全二

1、使用textscan函数格式化输入数据

当文本文件中的数据既有数值数据,又有文本数据,或者只有文本数据时,使用importdata或者 dlmread不能很好解决这些信息

c=textscan(fid,format,N)  N表示执行format的次数,默认情况,textscan以最大次数执行format格式转换,直至字符串或文件末尾

cmp %s And %q.txt'文件内容:"Hello World!"

fseek(fid,0,'bof');将文件指针指向文件的开始

ex10.m

fid=fopen('cmp %s And %q.txt','w');
fprintf(fid,'"Hello World!"');
fclose(fid);
clear fid;
fid=fopen('cmp %s And %q.txt','r');
fseek(fid,0,'bof');
s1=textscan(fid,'%s',1);
fseek(fid,0,'bof');
s2=textscan(fid,'%q',1);
fclose(fid);

>> s1{1}


ans = 


    '"Hello'


>> s2{1}
ans = 
    'Hello World!'

2、使用fscanf函数读取文本文件数据

A=fscanf(fielID,format,sizeA)

sizeA可以为整数,表示最多读取m个数值或字符串,  [m,n],表示最多读取m行n列数据

temp.txt文件内容

Day1
temp1=13
temp2=25
temp3=16
Day2
temp1=14
temp2=25
temp3=16
Day3
temp1=14
temp2=26
temp3=17

程序运行:

>> fid=fopen('temp.txt');
>> fseek(fid,0,'bof');
>> c=fscanf(fid,'Day1 temp1= %f temp2= %f temp3= %f',3);
>> fclose(fid);
>> c


c =


    13
    25
    16



你可能感兴趣的:(10,Matlab学习笔记)