如何将 CSV 文件导入 MATLAB?我正在处理的文件中的一行看起来像:
SUNW,2-Jan-98,1998,5,40.125,41.5
有 36 列和 10107 行。第一行包含列标题。似乎 MATLAB 不支持导入此类 CSV 文件。使用以下 textscan
函数将整个数据读入一个元胞数组。
data = textscan(fid, '%s %s %d %d %f %f', ...
'HeaderLines',1, 'Delimiter',',', 'CollectOutput',1);
有没有办法将每一列的数据读入不同的变量?
最佳答案
textscan
documentation 中的示例 6似乎涵盖了您感兴趣的用例:
Using a text editor, create a comma-delimited file data2.csv that contains the lines
abc, 2, NA, 3, 4 // Comment Here def, na, 5, 6, 7
Designate the input that textscan should treat as comments or empty values:
fid = fopen('data2.csv'); C = textscan(fid, '%s %n %n %n %n', 'delimiter', ',', ... 'treatAsEmpty', {'NA', 'na'}, ... 'commentStyle', '//'); fclose(fid);
textscan returns a 1-by-5 cell array C with the following cells:
C{1} = {'abc'; 'def'} C{2} = [2; NaN] C{3} = [NaN; 5] C{4} = [3; 6] C{5} = [4; 7]
虽然它没有明确地将每一列分配给一个单独的变量,但您可以轻松地执行类似 col1 = C{1};
的操作。
关于matlab - 在 MATLAB 中导入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959688/