Search code examples
stringmatlabcharactercell

Remove characters from a cell array of strings (Matlab)


I have a cell array of strings. I need to extract say 1-to-n characters for each item. Strings are always longer than n characters. Please see:

data = { 'msft05/01/2010' ;
         'ap01/01/2013' }

% For each string, last 10 characters are removed and put it in the next column

answer = { 'msft' '05/01/2010' ;
           'ap'   '01/01/2013' }

Is there a vectorized solution possible? I have tried using cellfun but wasn't successful. Thanks.


Solution

  • data = { 'msft05/01/2010' ;
             'ap01/01/2013' };
    for i = 1:length(data)
        s = data{i};
        data{i} = {s(1:end-10) s(end-9:end)};
    end
    

    Sorry, didn't notice that you need vectorized... Perhaps I can suggest only one-liner...

    data = cellfun(@(s) {s(1:end-10) s(end-9:end)}, data, 'UniformOutput', false);