我能够读取文本文件,并且能够逐行或全部读取。但是我需要在向量中添加一些列。例如,如果这是整个文件:
1000011112222
2000011112222
3000011112222
4000011112222
5000011112222
我需要读取每行中的第一个数字(第一列为1 2 3 4 5),但它必须是向量。然后,我需要从第二列到第五列进行阅读,并将它们放在一个mtrix中,从第六列到第八列放在另一个矩阵中,依此类推。有什么简单的主意吗?注意:所需的列数比本示例大得多(每个矩阵中不是4列,而是896列)
我的代码:
fid=fopen(filename, 'txt');
tline = fgetl(fid);
while ischar(tline)
vnum = sscanf(tline);
fnum=sscanf(tline, 'f %d %d %d');
tline = fgetl(fid);
end
设置1(如示例数据中所列)
这可能是一种基于fileread
将文本文件读取为字符串数据的方法-
%// Read in data as a char array
char_data = fileread(file_name)
%// Convert it to a properly formatted char array with `char()`
%// and then to a numeric array with "- '0'"
num_data = char(strsplit(char_data).') - '0' %//'
%// Finally, separate out columns as per the set requirements
var1 = num_data(:,1)
var2 = num_data(:,2:5)
var3 = num_data(:,6:8)
代码运行-
var1 =
1
2
3
4
5
var2 =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
var3 =
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
设置2
根据OP在下面发布的评论,如果您具有这样的文本文件设置-
0.0000000e+00 2.3000000e+01 2.1660000e+01 2.0840000e+01 ....
0.2000000e+00 2.3500000e+01 2.1660000e+01 2.0840000e+01 ....
0.3000000e+00 2.3600000e+01 2.1660000e+01 2.0840000e+01 ....
您可以importdata
使用单元格数组读取数据,根据列间距拆分数据,然后像以前的方法一样从中收集特定的列。这在下面实现-
%// Read in data into a cell array of strings;
%// Trim whitespaces around it, should there be any
cell_data = strtrim(importdata(file_name,''))
%// Separate out columns within each cell of the cell array
cellsep_data = cellfun(@(x) strsplit(x),cell_data,'Uni',0)
%// Concatenate data from all cells into a "single-level" cell array
cellsep_data1 = vertcat(cellsep_data{:})
%// Convert to numeric array
num_data = str2double(cellsep_data1)
%// Finally, separate out columns as per th set requirements
var1 = num_data(:,1)
var2 = num_data(:,2:5)
var3 = num_data(:,6:8)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句