Matlab:从.csv文件只读标题行 [英] Matlab: read only header line from a .csv-file

查看:1708
本文介绍了Matlab:从.csv文件只读标题行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个myfile.csv变量名称在第一行和十进制数字在下面的。在Matlab中,我想分别读取标题行和十进制数。到目前为止,我已经做了以下提取标题行:

Assume there's a myfile.csv with variable names in the first row and decimal numbers in the following ones. In Matlab I'd like to read the header line and the decimal numbers separately. So far, I've been doing the following to extract the header line:

fid = fopen('myfile.csv');
a = textscan(fid,'%s','Delimiter','\n');
b = a{1,1};
fclose(fid);
c = textscan(b,'%s','Delimiter',',');
d = c{1}

然后,我使用csvread命令提取数字部分的文件。但应该有一个(很多)更容易的方法来做到这一点!首先,我不想读取整个文件(如 a = textscan(fid,'%s','Delimiter','\\\
');
)只提取第一行。第二,它看起来错误使用7行代码来做 - 可以做更少?

Then, I use the csvread command to extract the numerical part of the file. But there should be a (much) easier way to do it! First, I don't want to read the whole file (as with a = textscan(fid,'%s','Delimiter','\n');) to extract only the first line. Second, it looks wrong to use 7 lines of code to do it - can it be done with less?

我将非常感谢任何建设性的建议。

I'd be thankful for any constructive suggestions.

推荐答案

使用 fopen 打开文件,读取 textscan 的标题行,使用 fscanf ,最后调用 fclose - 总共只有4行:)示例输入文件:

Open the file with fopen, read the header line with textscan, read the decimal numbers with fscanf, and call fclose in the end - only 4 lines in total :) Example input file:

Weight,Size,Count
1,2,3
4,5,6
7,8,9
10,11,12

读取此档案:

fid = fopen('myfile.csv', 'r');
header = textscan(fid, '%[^,],%[^,],%[^,\r\n]', 1);
data = transpose(fscanf(fid, '%g,%g,%g\n', [3, Inf]));
fclose(fid);

for i = 1 : 3; disp(['"' cell2mat(header{i}) '"']); end;
disp(data);

请注意,由 fscanf 读取的数据需要(我强调这是通过写 transpose 而不是')。输出:

Note that the data read by fscanf need to be transposed (I emphasized this by writing transpose instead of '). The output:

"Weight"
"Size"
"Count"
     1     2     3
     4     5     6
     7     8     9
    10    11    12

这篇关于Matlab:从.csv文件只读标题行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆