Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
 
 
主题工具 显示模式
旧 2019-12-14, 20:13   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 导入具有混合数据类型的CSV文件

我在MATLAB上工作了几天,而且很难将CSV文件导入矩阵。

我的问题是我的CSV文件几乎只包含字符串和一些整数值,因此csvread()不起作用。 csvread()仅与整数值csvread() 。

如何将我的字符串存储在某种二维数组中以自由访问每个元素?

这是我需要的CSV示例文件:

04;abc;def;ghj;klm;;;;; ;;;;;Test;text;0xFF;; ;;;;;asdfhsdf;dsafdsag;0x0F0F;; 最主要的是空单元格和单元格中的文本。如您所见,结构可能会有所不同。



回答:

对于这种情况,当您知道CSV文件中将有多少列数据时,像Amro建议的那样简单地调用textscan将是您的最佳解决方案。

但是,如果您不知道先验文件中有多少列,则可以使用更通用的方法,就像我在以下函数中所做的那样。我首先使用函数fgetl将文件的每一行读入单元格数组。然后,我使用了textscan函数,使用预定义的字段定界符将每一行解析为单独的字符串,并且现在将整数字段视为字符串(以后可以将其转换为数值)。这是生成的代码,放在函数read_mixed_csv :

function lineArray = read_mixed_csv(fileName, delimiter) fid = fopen(fileName, 'r'); % Open the file lineArray = cell(100, 1); % Preallocate a cell array (ideally slightly % larger than is needed) lineIndex = 1; % Index of cell to place the next line in nextLine = fgetl(fid); % Read the first line from the file while ~isequal(nextLine, -1) % Loop while not at the end of the file lineArray{lineIndex} = nextLine; % Add the line to the cell array lineIndex = lineIndex+1; % Increment the line index nextLine = fgetl(fid); % Read the next line from the file end fclose(fid); % Close the file lineArray = lineArray(1:lineIndex-1); % Remove empty cells, if needed for iLine = 1:lineIndex-1 % Loop over lines lineData = textscan(lineArray{iLine}, '%s', ... % Read strings 'Delimiter', delimiter); lineData = lineData{1}; % Remove cell encapsulation if strcmp(lineArray{iLine}(end), delimiter) % Account for when the line lineData{end+1} = ''; % ends with a delimiter end lineArray(iLine, 1:numel(lineData)) = lineData; % Overwrite line data end end 在问题的示例文件内容上运行此功能将得到以下结果:

>> data = read_mixed_csv('myfile.csv', ';') data = Columns 1 through 7 '04' 'abc' 'def' 'ghj' 'klm' '' '' '' '' '' '' '' 'Test' 'text' '' '' '' '' '' 'asdfhsdf' 'dsafdsag' Columns 8 through 10 '' '' '' '0xFF' '' '' '0x0F0F' '' '' 结果是一个3×10的单元格数组,每个单元格有一个字段,其中缺失的字段由空字符串'' 。现在,您可以访问每个单元格或单元格组合以根据需要设置其格式。例如,如果要将第一列中的字段从字符串更改为整数值,可以按以下方式使用函数str2double

>> data(:, 1) = cellfun(@(s) {str2double(s)}, data(:, 1)) data = Columns 1 through 7 [ 4] 'abc' 'def' 'ghj' 'klm' '' '' [NaN] '' '' '' '' 'Test' 'text' [NaN] '' '' '' '' 'asdfhsdf' 'dsafdsag' Columns 8 through 10 '' '' '' '0xFF' '' '' '0x0F0F' '' '' 请注意,空白字段会产生NaN值。



更多&回答...
poster 当前离线   回复时引用此帖
 


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 23:21


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.