减少文本扫描中的表达式



关于数据,如:

Student_ID|Test1|Test2|Test3

1 91.5 89.2 77.3

2 88.0 67.8 91.0

3 76.3 78.1 92.5

4 96.4 81.2 84.6

如果我使用

fileID = fopen('grades.txt');
formatSpec = '%s';
N = 4;
C_text = textscan(fileID, formatSpec, N, 'delimiter', '|');

则Matlab将使用格式CCD_ 1读取列标题四次。

但是我怎么能用一种更简单的方式写像这样的东西呢

textscan(fileID, '%f %f %f %f %f %f %f %*f %f %f %f %f %f %f %f', 'delimiter', '|');我想读前七个浮动,忽略第八个浮动,读最后七个浮动?

一种方法是动态生成格式字符串,而不是硬编码:

formatSpec = [repmat('%f', 1, 7), '%*f', repmat('%f', 1, 7)];

然后可以将此格式字符串传递给textscan

另一种方法是读取以字符串形式包含数字的行,然后使用str2num将其转换为数值,并丢弃不需要的列,类似于以下内容:

C = textscan(fileID, '%s', 'delimiter', 'n');
vals = cell2mat(cellfun(@str2num, C{:}, 'UniformOutput', false));
vals(:, 8) = [];

p.S
你知道textscan有一个HeaderLines选项可以跳过文件开头的行吗?

最新更新