fhm
fhm

Reputation: 57

MATLAB: how to split cell arrays of different delimiter numbers?

Assume there is an input cell:

input=

"82.3 4.3 John"

"4.2 0.0001 Tim Taylor"

This is a 2by1 cell array. I need to split this to get a 2by3 array like:

"82.3" "4.3" "John"

"4.2" "0.0001" "Tim Taylor"

The split(input) or split(input,'\t') returns error as each row of cell includes different number of delimiters.

Upvotes: 2

Views: 2910

Answers (3)

gnovice
gnovice

Reputation: 125854

You can use split, but it will differ depending on whether you have a cell array containing character vectors or a cell array containing strings (I know, it's very confusing):

If your input is displayed like this:

input =

  2×1 cell array

    '82.3   4.3 John'
    '4.2    0.0001  Tim Taylor'

Then you have a cell array of character vectors, and you can split at the tabs like this:

str = split(input, char(9))

str = 

  2×3 string array

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


If your input is instead displayed like this:

input =

  2×1 cell array

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

Then you have a cell array of strings, and you need to concatenate the cells into a 2-by-1 array of strings before splitting at the tabs:

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

str = 

  2×3 string array

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


Note that I had to use char(9) to specify the ASCII tab character, and that the output in each case is a 2-by-3 array of strings.

Upvotes: 6

Xiangrui Li
Xiangrui Li

Reputation: 2426

This is not beautiful, but it does the job:

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

Upvotes: 1

Gryphon
Gryphon

Reputation: 549

The are several ways to do that

%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. As @Ander Biguri suggested, with strsplit

    out=cellfun(@(x) strsplit(x,'\t'), inp,'un',0); out=cat(1,out{:})
    
  2. With some file-import function, i.e. with 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{:})
    

Upvotes: 1

Related Questions