Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Michael
Michael le 13 Fév 2014
Commenté : Image Analyst le 14 Fév 2014
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

Réponse acceptée

Image Analyst
Image Analyst le 14 Fév 2014
str = 'I am new to matlab, and am struggling.'
theWords = allwords(str)
strArray=char(theWords{:})
theAcronym = strArray(:,1)'
  1 commentaire
Image Analyst
Image Analyst le 14 Fév 2014
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'

Connectez-vous pour commenter.

Plus de réponses (1)

Jan Orwat
Jan Orwat le 14 Fév 2014
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