MATLAB:如何拆分不同分隔符号的单元格数组?

时间:2017-09-12 18:02:08

标签: arrays string matlab split cell-array

假设有一个输入单元格:

{ _id: 59b5eebd33a3a833b6ac1386, _user: 59aff09a11011f0cfd8d7666, location: 'nother', availability: 'jhkvljh', price: 9860, __v: 0, items: [ { equipmentType: 'kbj;kj', make: ';jb', model: ';;jb', watts: 9860, bulb: 'kjbkj', condition: 'kjbkjb', _id: 59b5eebd33a3a833b6ac1387 }, { condition: 'houy', bulb: 'jhg', watts: 8907, model: 'mode', make: 'maker', equipmentType: 'smoquip', _id: 59b5f9cf13b37234ed033a75 } ] }

input=

"82.3 4.3 John"

这是一个2by1的单元格数组。我需要拆分它以获得2by3数组,如:

"4.2 0.0001 Tim Taylor"

"82.3" "4.3" "John"

"4.2" "0.0001" "Tim Taylor"split(input)返回错误,因为每行单元格包含不同数量的分隔符。

3 个答案:

答案 0 :(得分:5)

您可以使用split,但会有所不同,具体取决于您是cell array containing character vectors还是cell array包含strings(我知道,它是very confusing {3}}):

如果input显示如下:

input =

  2×1 cell array

    '82.3   4.3 John'
    '4.2    0.0001  Tim Taylor'

然后你有一个字符向量的单元格数组,你可以在这些标签上拆分:

str = split(input, char(9))

str = 

  2×3 string array

    "82.3"    "4.3"       "John"      
    "4.2"     "0.0001"    "Tim Taylor"


如果您的input显示如下:

input =

  2×1 cell array

    ["82.3  4.3 John"      ]
    ["4.2   0.0001  Tim Taylor"]

然后你有一个字符串的单元格数组,你需要在切换选项卡之前将单元格连接成一个2乘1的字符串数组:

str = split([input{:}].', char(9))

str = 

  2×3 string array

    "82.3"    "4.3"       "John"      
    "4.2"     "0.0001"    "Tim Taylor"


请注意,我必须使用char(9)来指定ASCII制表符,并且每种情况下的输出都是2乘3的字符串数组。

答案 1 :(得分:1)

有几种方法可以做到这一点

%Never remembered how to correctly insert whitespace characters
inp = {['82.3' char(9) '4.3' char(9) 'John'];['4.2' char(9) '0.0001' char(9) 'Tim Taylor']}
  1. 正如@Ander Biguri建议的那样,使用strsplit

    out=cellfun(@(x) strsplit(x,'\t'), inp,'un',0); out=cat(1,out{:})
    
  2. 使用一些文件导入功能,即使用textscan

    %with on-the-fly type conversion
    out = cellfun(@(x) textscan(x,'%f%f%s','delimiter','\t'), inp, 'un', 0); out = cat(1,out{:})
    %keeping all values as strings
    out = cellfun(@(x) textscan(x,'%s%s%s','delimiter','\t'), inp, 'un', 0); out = cat(1,out{:})
    

答案 2 :(得分:1)

这不是很漂亮,但它可以胜任:

clear output % make sure not exist
for i = 1:size(input,1)
    output(i,:) = cellstr(regexp(input{i}, '\t', 'split'));
end
相关问题