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

1 visualización (últimos 30 días)
Michael
Michael el 13 de Feb. de 2014
Comentada: Image Analyst el 14 de Feb. de 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

Respuesta aceptada

Image Analyst
Image Analyst el 14 de Feb. de 2014
str = 'I am new to matlab, and am struggling.'
theWords = allwords(str)
strArray=char(theWords{:})
theAcronym = strArray(:,1)'
  1 comentario
Image Analyst
Image Analyst el 14 de Feb. de 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'

Iniciar sesión para comentar.

Más respuestas (1)

Jan Orwat
Jan Orwat el 14 de Feb. de 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