Search code examples
arraysstringmatlabcell

How to write a one liner that converts string array input into cell array and appends additional cell array term?


Inspired by this question:

Matlab - how to read 2 bytes at a time

Defining

s= '778310098';

I wrote a one-liner:

c = reshape(reshape(s(1:2^(nextpow2(length(s))-mod(length(s),2))),2,[]).',[],2)

which outputs

c =

77
83
10
09

and takes me far, but no cigar, since my objective was to have the result as a cell array of strings, including the odd terminal element '8'.

I'm wondering how I could, as concisely as possible, turn the contents of the ouput char array into a cell array with entries

d{1} = '77'
d{2} = '83'
d{3} = '10'
d{4} = '09'

Also, I'd like to append the missing value (concisely), such that

d{5} = '8'

Solution

  • This works perfectly for the odd case:

    mat2cell(s, 1, [2*ones(floor(size(s, 2)/2)), mod(size(s,2), 2)])'
    

    but in the even case it will add an extra empty cell at the end. I suggest you just don't enforce a one-liner rule on yourself in this case.