Search code examples
matlabcellremoving-whitespace

How to remove white spaces in the beginning and the end in matlab?


I have a structure consisting of cells. I want to remove all white spaces in the beginning of each cell and in the end, and I want to preserve all the white spaces in between text in the cells. So if I have

s = '   bbb b bbbb   ' 

I want to obtain

s = 'bbb b bbbb' 

I want to apply this method to an unknown number of cells in this structure (for example 2x3), perhaps using a loop. Does anyone have an idea how to do it? I failed with regexp.


Solution

  • You can use strtrim() in combination with structfun() and cell-indexing:

    your_struct = structfun(@(x) strtrim(x{1}), your_struct);
    

    This only works if your struct has a layout like

    your_struct.a = {' some string  '};
    your_struct.b = {' some other string  '};
    ...
    

    If it has a different structure, say,

    your_struct.a = { {' some string  '}
                      {'   some other string '}};
    
    your_struct.b = { {' again, some string  '}
                      {'   again, some other string '}};
    
    ...
    

    You could try

    your_struct = structfun(@(x) ...
        cellfun(@strtrim, x, 'uni', false), ...
        your_struct, 'uni', false);