Please, help with Matlab code
3 views (last 30 days)
Show older comments
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.
Code to call function:
word=["cent", "centennial","century"];
longestword(word)
word=["love", "care","joy"];
longestword(word)
5 Comments
Answers (3)
per isakson
on 24 Apr 2021
Edited: per isakson
on 24 Apr 2021
Your function works just fine
longestword("Heat","Lakers","Warriors")
longestword("cent","centennial","century")
longestword("love","care","joy")
0 Comments
Clayton Gotberg
on 24 Apr 2021
I really like your first longestword function.
function out = longestword(word1, word2, word3)
% Matlab function that takes as inputs 3 words and return the word with
% the most number of characters (and the first in the list when they
% have the same length)
% set out to word1
out = word1;
% strlength is used to return the number of characters in input string
% if number of characters in word2 > out, set out to word2
if(strlength(word2) > strlength(out))
out = word2;
end
% if number of characters in word3 > out, set out to word3
if(strlength(word3) > strlength(out))
out = word3;
end
end
The error that you got when you ran it was because
word=["cent", "centennial","century"];
is one input, not three. Additionally, it doesn't look like there has to be a limit to the number of words that might be in the input, so you may want to write the code knowing that there might be any number of words in the input.
function out = longestword(input_words)
out = input_words(1);
for i = 2:length(input_words) % For each of the next input words until the last one
if strlength(input_words(i))>strlength(out) % If it's longer than the current output
out = input_words(i); % Change the output to the new input word
end
end
end
If you always know there will be three words, you can use the original format, but instead of word1, word2, word3, use word(1), word(2), word(3) to grab the first through third words in the one input array.
0 Comments
Image Analyst
on 24 Apr 2021
What is the name of your m-file? It had better not be longestword.m or longest_word.m.
Also, you appear to be calling the function longestword(), yet there is no such function. You named your function longest_word() with an underline in it.
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!