Matlab - 将.dat文件导入数组

时间:2013-09-21 21:46:15

标签: arrays matlab import

我仍然是Matlab的新手,但由于某些原因,文档对此没有任何帮助。

我有一个.dat文件,我希望将其转换为_行的6列数组(行数会根据生成.dat文件的程序而变化)。我需要做的是从第1行第2列(x维度)和第1行第4列(y维度)获取此数组将用于生成的图像的维度。在Matlab中使用“导入数据”工具时,这可以正常工作:

enter image description here

但是我需要程序自动完成。如果第一行不存在,我很确定我可以使用fscanf将数据放入数组中,但图像尺寸是必要的。

知道我需要使用什么呢?

1 个答案:

答案 0 :(得分:0)

您可以使用textscan。第一次调用此函数将处理第一行(即获取文件的维度),第二次调用文件的剩余部分。第二个调用使用repmat来声明格式规范:%f,意为double,重复nb_col次。选项CollectOutput将连接单个数组中的所有列。请注意,textscan可以读取整个文件而不指定行数。

代码是

fileID = fopen('youfile.dat');     %declare a file id

C1 = textscan(fileID,'%s%f%s%f');   %read the first line
nb_col = C1{4};                     %get the number of columns (could be set by user too) 

%read the remaining of the file
C2 = textscan(fileID, repmat('%f',1,nb_col), 'CollectOutput',1);

fclose(fileID);                     %close the connection

如果列数已修复,您只需执行

即可
fileID = fopen('youfile.dat');
C1 = textscan(fileID,'%s%f%s%f');   %read the first line
im_x = C1{2};                       %get the x dimension 
im_y = C1{4};                       %get the x dimension 

C2 = textscan(fileID,'%f%f%f%f%f%f%*[^\n]', 'CollectOutput',1);
fclose(fileID);

格式规范%*[^\n]会跳过剩余的一行。

相关问题