如何在matlab中从文本文件创建2X5矩阵

时间:2014-03-20 09:25:06

标签: matlab

我正在尝试从文本文件中获取5X2矩阵。

对于示例:

0_0     1_0
0_200   1_200
0_400   1_400
0_600   1_600
0_800   1_800

这是我目前使用的代码

[filename,pathname]= uigetfile({'*.txt'});
set(handles.temp1,'String',fullfile(pathname,filename));
chosenfile=get(handles.temp1,'String');

fid=fopen(chosenfile);

allcoordinates=textscan(fid,'%s,%s','whitespace','\n');    
fclose(fid);

此代码将生成一个5X1矩阵,如下所示:

 0_01_0
 0_2001_200
 0_4001_400
 0_6001_600
 0_8001_800

1 个答案:

答案 0 :(得分:3)

可悲的是,对于文件解释最有效的方法是非常保守,依赖于'固定例程'例如textscandlmread和类似的。

这不是因为这些例程执行得很糟糕,因为文本文件中的数字格式很少标准化,基本上,每个人都在现场发明新标准。

您无法设计一个始终适用于所有文本文件的例程。我认为The Mathworks使用dlmread和类似的工作做得非常不错,但是,你刚刚提出了数字格式的另一个标准,这个标准过于难以一次解释{{ 1}}或textscan或其他人。因此,保守:只是阅读它没有太多的麻烦,并自己做转换。

例如:

dlmread

结果:

%// Read data
fid = fopen('yourFile.txt', 'r');
    C = textscan(fid, '%s %s');
fclose(fid);

%// Replace all underscores with '.', and convert to 'double'    
C = str2double(strrep([C{:}],'_','.'))