Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
berndh Avatar asked Aug 22 '12 09:08

berndh


People also ask

How do you get rid of leading and trailing white spaces?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

What is a trailing whitespace?

Trailing whitespace. Description: Used when there is whitespace between the end of a line and the newline.

How do you strip a string in Matlab?

Description. newStr = strip( str ) removes all consecutive whitespace characters from the beginning and end of str , and returns the result as newStr . newStr = strip( str , side ) removes all consecutive whitespace characters from the side specified by side .

What does Isspace do in Matlab?

TF = isspace( A ) returns a logical array TF . If A is a character array or string scalar, then the elements of TF are logical 1 ( true ) where corresponding characters in A are space characters, and logical 0 ( false ) elsewhere. isspace recognizes all Unicode® whitespace characters.


1 Answers

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);
like image 163
Rody Oldenhuis Avatar answered Oct 19 '22 19:10

Rody Oldenhuis