views:

85

answers:

2

Is there an easy way to create an acronym from a string in MATLAB? For example:

'Superior Temporal Gyrus' => 'STG'
+6  A: 

If you want to put every capital letter into an abbreviation...

... you could use the function REGEXP:

str = 'Superior Temporal Gyrus';  %# Sample string
abbr = str(regexp(str,'[A-Z]'));  %# Get all capital letters

... or you could use the functions UPPER and ISSPACE:

abbr = str((str == upper(str)) & ~isspace(str));  %# Compare str to its uppercase
                                                  %#   version and keep elements
                                                  %#   that match, ignoring
                                                  %#   whitespace

... or you could instead make use of the ASCII/UNICODE values for capital letters:

abbr = str((str <= 90) & (str >= 65));  %# Get capital letters A (65) to Z (90)


If you want to put every letter that starts a word into an abbreviation...

... you could use the function REGEXP:

abbr = str(regexp(str,'\w+'));  %# Get the starting letter of each word

... or you could use the functions STRTRIM, FIND, and ISSPACE:

str = strtrim(str);  %# Trim leading and trailing whitespace first
abbr = str([1 find(isspace(str))+1]);  %# Get the first element of str and every
                                       %#   element following whitespace

... or you could modify the above using logical indexing to avoid the call to FIND:

str = strtrim(str);  %# Still have to trim whitespace
abbr = str([true isspace(str)]);


If you want to put every capital letter that starts a word into an abbreviation...

... you can use the function REGEXP:

abbr = str(regexp(str,'\<[A-Z]\w*'));
gnovice
Regexp! Regexp! Also: http://xkcd.com/208/
Jonas
@Jonas: Wheeeeee[taptaptap]eeeeee!
gnovice
Nice answer to a very vague question
Kena
A: 

thanks, also this:

s1(regexp(s1, '[A-Z]', 'start'))

will return abbreviation consisting of capital letters in the string. Note the string has to be in Sentence Case

Ali
The `'start'` option is actually unnecessary, since by default the first argument returned from REGEXP will be the starting indices of matches.
gnovice