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 个评论
Daniel Pollard
2021-4-23
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?
Walter Roberson
2021-4-23
if (1+1)>length(i_spaces)
Coding (1+1) is suspicious. It would seem more likely to be
if (i+1)>length(i_spaces)
Marj Monique Cabical
2021-4-23
Daniel Pollard
2021-4-23
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.
Jan
2021-4-23
You did not mention, why you assume, that there is an error. This is a very useful information.
Marj Monique Cabical
2021-4-24
Marj Monique Cabical
2021-4-24
Walter Roberson
2021-4-24
You are expected to write longestword yourself.
Be careful about longestword compared to longest_word
回答(1 个)
Jan
2021-4-23
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?
类别
在 帮助中心 和 File Exchange 中查找有关 Language Support 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
