0

我有一个包含 100 行的数据文件,格式如下

0,device1,3
1,device2,33
2,device3,3
3,device4,34
...
99,device100,36

现在我希望将它们读入100x3MATLAB 中的单元格数组。我做了以下事情:

allData = textscan(fID,'%s %s %f', 'delimiter', ',');

然后,我注意到这allData是一个1x3单元格数组,每个项目都是另一个100x1单元格数组。(前两列是字符串型元胞数组,而第三列是双精度型元胞数组)

换句话说,读取结果是一个nested数组,我不想要。

如何 100x3在阅读时直接实现单元阵列?

4

2 回答 2

2

有了这个textscan,变量allData看起来像(只有 4 行)这样:

allData = 
    {4x1 cell}    {4x1 cell}    [4x1 double]

当所有数据具有相同类型时,您只能textscan通过选项直接合并到单个单元格数组中。'CollectOutput'

一种可能的解决方法,不幸的是,它将所有数字数据转换为双精度(在您的情况下不是问题),

C = cell(numel(allData{1}),numel(allData));
areCells = cellfun(@iscell,allData);
C(:,areCells) = [allData{areCells}];
C(:,~areCells) = num2cell([allData{~areCells}])
C = 
    '0'    'device1'    [ 3]
    '1'    'device2'    [33]
    '2'    'device3'    [ 3]
    '3'    'device4'    [34]

同样,这样做的缺点是最后一条语句会将所有非单元类型(例如 uint8、char 等)转换为双精度类型。为避免这种可能的转换:

% after copying cell array data (areCells) as above, but before ~areCells data
Cn = arrayfun(@(ii)num2cell(allData{ii}),find(~areCells),'uni',0);
C(:,~areCells) = [Cn{:}];
于 2014-02-26T23:42:39.077 回答
1

代码 -

sz = 100;                         % Line count
out=cell(sz,size(allData,2));             
for k = 1:size(allData,2)
    t1 = allData(k);
    t2 = [t1{:}];
    if isnumeric(t2)              % Takes care of floats
        out(:,k) = num2cell(t2);
    else
        out(:,k) = t2
    end
end

因此,前四行将显示为 -

out = 

    '0'    'device1'    [ 3]
    '1'    'device2'    [33]
    '2'    'device3'    [ 3]
    '3'    'device4'    [34]
于 2014-02-26T22:50:32.877 回答