Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format strings for use as structure field names in MATLAB?

I want to remove hyphens (-), slashes (/) and white space () from a string name(i) so that I can use it as a structure field name.

This is the ugly way I am currently doing it using the function strrep:

cell2mat(strrep(strrep(strrep(name(i), '-',''),'/',''),' ', ''))

I have also tried other variations, such as:

strrep(name(i),{'-','/'},{'',''});
strrep(name(i),['-','/'],['','']);

What is a more efficient way of doing this?

like image 454
Elpezmuerto Avatar asked Nov 16 '10 18:11

Elpezmuerto


Video Answer


1 Answers

Note: I'm guessing your variable name is a cell array of strings, in which case you will want to use {} (i.e. content indexing) instead of () (i.e. cell indexing) to get the strings from it...

As with many problems in MATLAB, there are a number of different ways you can solve this...


Option 1: You could use the function REGEXPREP. The following removes hyphens, forward slashes, and whitespace:

newName = regexprep(name{i},'[-/\s]','');

The benefit here is that the \s will match and replace all whitespace characters, which includes a normal space (ASCII code 32) as well as tabs, newlines, etc..

If you want to be safe and remove every character that is not valid in a MATLAB variable/field name, you can simplify the above to this:

newName = regexprep(name{i},'\W','');


Option 2: If you don't need to worry about removing anything other than the 3 characters you listed, you could use the function ISMEMBER like so:

newName = name{i};
newName(ismember(newName,'-/ ')) = [];


Option 3: If you want to just keep everything that is an alphanumeric character and dump the rest (hyphens, whitespace, underscores, etc.), you could use the function ISSTRPROP:

newName = name{i};
newName = newName(isstrprop(newName,'alphanum'));
like image 154
gnovice Avatar answered Sep 20 '22 14:09

gnovice