Please, help with Matlab code
189 views (last 30 days)
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).
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:
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;
% if number of characters in word3 > out, set out to word3
if(strlength(word3) > strlength(out))
out = word3;
The error that you got when you ran it was because
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
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.
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.