How to remove spaces at the beginning and at the end in Matlab?

I have a cell structure. I want to remove all white spaces at the beginning of each cell and at the end, and I want to keep all the spaces between the texts in the cells. Therefore if i have

s = '   bbb b bbbb   ' 

I want to receive

s = 'bbb b bbbb' 

I want to apply this method to an unknown number of cells in this structure (e.g. 2x3), possibly using a loop. Does anyone have an idea how to do this? I was unable to complete regexp.

+5
source share
4 answers

You can use strtrim()in combination with structfun()and indexing cells:

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

This only works if your structure has a layout, for example

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

If it has a different structure, let's say

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

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

...

You can try

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

a, do:

 newmatrix = cellfun(@strtrim, a, 'UniformOutput', false)
0

A - , , :

New_A=structfun(@strtrim,A,'UniformOutput',false)
0
source

strtrim doesn't always care about the end of the line for me, so I use deblank

therefore, if strtrim did not do everything you wanted, you can use this with deblank to get what you want.

0
source

All Articles