Beginner - using a function to find last word of a phrase?

1 次查看(过去 30 天)
I'm new to matlab, and am struggling. In this case, I am told to find a acronym function that would give the acronym of any phrase I input.
"function acr = acronym(phrase)".....
....is given, and if evaluated correctly, typing in acronym('i love matlab') and acronym('the ball is red') both yield 'ilm' and 'tbir'.
Some guidance would be appreciated as to how to finish the acr function correctly so as to be able to yield acronyms for any phrase from one m.file. Thank you

采纳的回答

Image Analyst
Image Analyst 2014-2-14
str = 'I am new to matlab, and am struggling.'
theWords = allwords(str)
strArray=char(theWords{:})
theAcronym = strArray(:,1)'
  1 个评论
Image Analyst
Image Analyst 2014-2-14
By the way, to do what you asked in your subject, instead of the different question in your body, to get the last word in the phrase you can just do
str = 'I am new to matlab, and am struggling.'
theWords = allwords(str)
lastWord = char(theWords{end}) % Extracts 'struggling'

请先登录,再进行评论。

更多回答(1 个)

Jan Orwat
Jan Orwat 2014-2-14
Hello Michael,
very useful function which can solve your problem is regexprep. You can read more about this function by typing doc regexprep. It is also good to know more about regular expressions. Just press F1 and search in documentation for this topic in MATLAB.
Using function regexprep you can easily find acronym to given phrase by searching first letters of words in phrase:
acr=regexprep(phrase,' *\<(.).*?\>','$1');
Which means that regexprep takes string phrase and look for substrings
' *\<(.).*?\>'
in means more or less: (any number of spaces)+(a word which contains a sign (stored in token) and any (smallest possible) set of other signs until the end of word) and replaces matches by first tokens for all matches - first letters. Lecture of documentation and some experiments will definitely help you to understand how regular expressions works.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by