您的位置:首页 > 编程语言 > MATLAB

【matlab】读生成的指定路径下的数据文件并保存到矩阵中

2016-07-01 16:01 411 查看
5
 
8   2   2   2   2  
 
0   4   1   2   0  
10  0   10  6   5  
0   2   0   8   0  
0   3   9   0   0  
8   3   0   0   0  

 

 

问题:将以上保存为.dat文件格式的文件读入文件中,分别用三个矩阵存储结果。准备用fopen命令进行操作,准备采用行读入的方式进行,难点在于最后一个矩阵的读入,因为有多行数据,这儿采取使用for循环,元胞数组暂时存入,让后赋值矩阵中。

代码如下:

clc
clear all
n=[];
l=[];
f=[];
filename=['E:\Writing paper\CAP\my instance\',num2str(5),'_',num2str(60),'.dat'];
% a file froma specific file
disp(filename);
fid=fopen(filename);  %fopen function
n=str2num(fgetl(fid)); % read the first row data. The str2num is very importantfor the following for.
fgetl(fid);            % this line is empty
l=str2num(fgetl(fid));          %read the third line.
fgetl(fid);           % this line is empty
%% read the remainingrow. It is f matrix.
for i=1:n
    a{i}=fgetl(fid);
    f(i,:)=str2num(a{i});
end
%%
fclose(fid);   %closethe file
 

注意:善于利用str2num和num2str命令,因为文件名称数据类型是字符形式,而矩阵中数据类型因为数字。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: