MATLAB reverse sentence problem Now it\'s your turn, again. Write a function (re
ID: 3574057 • Letter: M
Question
MATLAB reverse sentence problem
Now it's your turn, again. Write a function (reverse_sentence .m) that takes a single input argument which is a string containing a sentence (a sequence of words) and returns a single output argument which is a string containing the words in the input string in reverse order. For example, on input ' the quick brown fox jumps over the lazy dog', the function should return ' dog lazy the over jumps fox brown quick the'. Remember to think before you code. Have pencil and paper next to you and sketch your algorithm as pseudocode or flow diagram. I will get you started on this one: Split the sentence at whitespace to form an array of words. Reverse the array of words. Construct the reversed sentence by joining the words in the array with spaces.Explanation / Answer
a.Find the length of the string
b.Use MATLAB built in function strtok to separate the first word and the remaining sentence.
For instance, the input string is ‘the quick brown fox jumps over the lazy dog’.
[Token,remain]=strtok(input_string);
The variable token will contain ‘the’
And the variable remain will contain ‘quick brown fox jumps over the lazy dog’.
Use while loop to extract all the strings.
c. In the first iteration, the string in the token variable is concatenated with a empty variable ‘t’.
Now t has ‘the’.
In the second iteration, token has ‘quick’ and remain has ‘brown fox jumps over the lazy dog’.
Now the string ‘quick’ is concatenated with the string t.
d. Here to preserve the space ,the syntax [string2, ‘ ’,string1] is used.
The length of the input_string gets reduced during each iteration and finally when all the strings are extracted, the loop is terminated.
MATLAB CODE:
%To reverse the words position in a string
str='the quick brown fox jumps over the lazy dog';
%str=fliplr(str);
len=length(str);
t='';
while(len>0)
[token,str]=strtok(str);
len=length(str);
%token=fliplr(token);
%t=[token,' ',t];
t=[' ',token,t];
end
display(t);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.