I need to create an m-file in Matlab that contains the following function:
function acr = acronym(phrase)
This function should compute and returns the acronym of the phrase as the result of the function; that is, if someone types any phrase in Matlab, this function should return an acronym consisting of the first letter of every word in that phrase. I know that it’s a simple function, but my coding experience is very limited and any help would be appreciated; thanks in advance.
This is a great place to use regular expressions. The function regexp
takes in a string and a regular expression and returns the starting indices for each substring that matches the regular expression. In this case, you want to match any character that starts a word. \<expr
matches expr
when it occurs at the start of a word (See the documentation for regexp
). A period matches any character. So the regular expression to match the first character of any word is \<.
.
Thus,
regexp(phrase,'\<.')
will return the indices for the first letter of each word in phrase
. So an acronym function could be:
function acr = acronym(phrase)
ind = regexp(phrase, '\<.');
acr = upper(phrase(ind));
end
Or even just
function acr = acronym(phrase)
acr = upper(phrase(regexp(phrase, '\<.')));
end
You can use textscan
to read a formatted text file as well as a formatted string. Then you just have to keep the first letter of each word:
phrase='ceci est une phrase';
words=textscan(phrase,'%s','delimiter',' ');
words=words{:};
letters=cellfun(@(x) x(1),words);
acronym=upper(letters');
function output = acronym( input )
words_cell = textscan(input,'%s','delimiter',' ');
words = words_cell{ : };
letters = cellfun(@(x) textscan(x,'%c%*s'), words);
output = upper(letters');
end
EDIT: Just noticed a very similar answer has already been given!
精彩评论