Hi, what could be the error in this program?

Write a function named longestword that is use to compare words from the string vector named as word. The user will input the string vector word and the function will return the value of variable longest, the word with the most number of characters (and the first in the list when they have the same length).
Sampla output:
>>>longestword("Heat","Lakers","Warriors")
Warriors
Note: The following are the matlab functions that you can use in your script:
length=use to return the number of elements in a string vector.
strength=use to return the number of characters in string.
Function:
% Use if-elseif-else statement
longestword=longest_word(word)
code=double(phrase)
i_space=find(code==32)
word=char(code(1:i_spaces(1)))
for i=1:length(i_spaces)
if (1+1)>length(i_spaces)
break
elseif length(code(i_spaces(i)+1:i_spaces(1)))>length(word)
word=char(code(i_spaces(i)+1:i_spaces(1)));
end
end
Code to call you function:
word=["cent", "centennial","century"];
longestword(word)
word=["love", "care","joy"];
longestword(word)

8 Comments

I don't understand what your question is. You ask what's wrong with the code, but we can't run it because you haven't defined longest_word or phrase for us.
Can you be a bit clearer? Does the code return an error? If so, what does it say?
if (1+1)>length(i_spaces)
Coding (1+1) is suspicious. It would seem more likely to be
if (i+1)>length(i_spaces)
I would like to ask what's wrong with my code.
What makes you think there's anything wrong with it. As I said, we can't test it, so you have to help us out so we can help you.
You did not mention, why you assume, that there is an error. This is a very useful information.
Can you please suggest another code too?
You are expected to write longestword yourself.
Be careful about longestword compared to longest_word

Sign in to comment.

Answers (1)

Instead of converting the CHARs to doubles and searching for 32, and converting back to CHARs, you can search for the space directly:
i_space=find(word == ' ')
word = word(1:i_space(1)) % not trailing s "i_spaces"
But what happens, if the word does not contain a space? Then FIND replies the empty matrix. And if a space is found, word will contain it. You would need i_space(1)-1 instead.
In the description I find the command:
longestword("Heat","Lakers","Warriors")
This means, that a number of inputs are provided. In the code you split a string at the spaces manually. Later on you write:
word=["cent", "centennial","century"];
longestword(word)
This means, that a string array is provided. So what are the actual inputs?

Categories

Asked:

on 23 Apr 2021

Commented:

on 24 Apr 2021

Community Treasure Hunt

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

Start Hunting!