更新
使用新的示例输入,我可以确认没有任何内置方法可以正常工作。这是使用textscan 和reshape 的解决方案:
fid = fopen('ex1.csv');
inputMatrix = textscan(fid, '%s', 'delimiter', ',');
fclose(fid);
inputMatrix = reshape(a{1}, 3, [])'; %'//assuming 3 columns in file
>> inputMatrix
'A' 'B' 'C'
'1' '1' '1'
'2' '2' [1x2 char] %//the 2nd char is "\r"
'3' '3' [1x2 char]
或者,当方便的功能不起作用时,我通常只是恢复到老式的文件读取方式:
fid = fopen('ex1.csv');
inputMatrix = {};
while ~feof(fid)
line = fgetl(fid);
inputMatrix(end+1,:) = strsplit(line, ',');
end
fclose(fid);
>> inputMatrix
inputMatrix =
'A' 'B' 'C'
'1' '1' '1'
'2' '2' '2'
'3' '3' '3'
注意,这样做的好处是不关心有多少列,而且也不包括\r。
在任何情况下,您可能希望数字是数字矩阵而不是字符串的单元矩阵。对str2double 的简单调用将为您完成此操作(它会巧妙地忽略任何\r):
str2double(inputMatrix(2:end,:))
上一个
如果没有示例文件,我只能根据我在本地创建的简单输入提出建议,在我看来,importdata 和 load 都可以工作,具体取决于您输入数据的结构。
示例输入 1:
>> fid = fopen('ex1.csv', 'w');
>> fprintf(fid, '1,1,1\n');
>> fprintf(fid, '2,2,2\r\n');
>> fprintf(fid, '3,3,3\n');
>> fclose(fid);
>> a = importdata('ex1.csv')
ans =
1 1 1
2 2 2
3 3 3
>> a = load('ex1.csv')
ans =
1 1 1
2 2 2
3 3 3
示例输入 2:
>> fid = fopen('ex2.csv', 'w');
>> fprintf(fid, '1,1,1\n');
>> fprintf(fid, '2,2,2\r\n');
>> fprintf(fid, '3,3\n');
>> fclose(fid);
>> a = importdata('ex2.csv')
ans =
1 1 1
2 2 2
3 3 NaN
>> a = load('ex2.csv')
Error using load
Number of columns on line 3 of ASCII file ex2.csv must be the same as previous lines.