Search code examples
regexstringmatlabacronym

How can I create an acronym from a string in MATLAB?


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

'Superior Temporal Gyrus' => 'STG'

Solution

  • 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*'));