textscan()读取结果是一个嵌套的单元阵列? [英] textscan() reading result is a nested cell array?

查看:314
本文介绍了textscan()读取结果是一个嵌套的单元阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


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


现在我希望他们读入 100x3 细胞在MATLAB阵列。我做了以下内容:

  ALLDATA = textscan(FID,'%s%S%F','分隔符','');

然后,我注意到 ALLDATA 1×3 单元阵列,每个项目是另一个 100X1 单元阵列。 (前两列是串型单元阵列,而第三列是双型电池数组)

在换句话说,读取结果是嵌套阵列,这是我不想要的。

请问有什么可以直接实现 100x3 单元阵列,而读?


解决方案

通过了 textscan ,变量 ALLDATA 看起来像(只有4行)这样的:

  = ALLDATA
    {4X1细胞} {4X1细胞} [4X1双]

您只能合并成一个单一的单元阵列直接与 textscan 通过'CollectOutput 选项时,所有数据具有相同的类型。

一个可能的解决方法,不幸的是将所有数字数据翻番(而不是你的情况有问题),

  C =细胞(numel(ALLDATA {1}),numel(ALLDATA));
areCells = cellfun(@ iscell,ALLDATA);
C(:,areCells)= [{ALLDATA} areCells]。
C(:,〜areCells)= num2cell([ALLDATA {〜areCells}])
C =
    '0''设备1'[3]
    '1''设备2'[33]
    '2''设备3'[3]
    '3''device4'[34]

此外,这样做的缺点是最后的语句将转换所有非细胞类型(例如UINT8,焦炭等)转换成双打。为了避免这种可能的转换:

 复制单元阵列数据(areCells)如上%后,但在此之前〜areCells数据
CN = arrayfun(@(ⅱ)num2cell(ALLDATA {二}),找到(〜areCells),'单向',0);
C(:,〜areCells)= [CN {:}];

I have a data file containing 100 lines with the following format

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

Now I wish to read them into a 100x3 cell array in MATLAB. I did the following:

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

Then, I noticed that allData is a 1x3 cell array with each item being another 100x1 cell array. (The first two columns are string-type cell arrays, whereas the third column is double-type cell array)

In other words, the reading result is a nested array, which I don't want.

How may I achieve 100x3 cell array directly while reading?

解决方案

With that textscan, the variable allData looks something like (just 4 rows) this:

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

You can only merge into a single cell array directly with textscan via the 'CollectOutput' option when all data has the same type.

One possible workaround, which unfortunately converts all numeric data to double (not a problem in your case),

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]

Again, the drawback of this is that the last statement will convert all non-cell types (e.g. uint8, char, etc.) into doubles. To avoid this possible conversion:

% 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{:}];

这篇关于textscan()读取结果是一个嵌套的单元阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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