【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命令,因为文件名称数据类型是字符形式,而矩阵中数据类型因为数字。
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命令,因为文件名称数据类型是字符形式,而矩阵中数据类型因为数字。
相关文章推荐
- garbor 滤波 matlab 代码
- matlab混编C++
- 【matlab】如何产生特定格式的随机数,并保存结果
- MATLAB参数估计normfit()函数和mle()函数
- C++与Matlab混合编程总结(Mat mxArray mwArray转换)
- 一个matlab里的排列组合或者说是循环嵌套的层数不定的问题
- MATLAB工具包安装步骤
- matlab 也能干大事 —— 九等分一幅图像
- 基于MATLAB的高等数学 求二阶导
- 基于MATLAB的高等数学 判断函数是否可导
- 基于MATLAB的高等数学 求导数后求值
- 基于MATLAB的高等数学 复合函数求导
- 基于MATLAB的高等数学 求函数的左,右导数
- 基于MATLAB的高等数学 判断高阶无穷小
- 基于MATLAB的高等数学 极坐标系:阿基米德线,心形线的绘制
- LIBSVM学习(一)在Matlab环境下安装LIBSVM
- MATLAB抠图
- 图像序列合成视频(matlab)
- 基于MATLAB求解矩阵的正交补矩阵
- 和matlab一样的轻量级