-1

In the following code, I check to see if the first letter is in the dictionary of words and if the length of the word matches. If it does, return the word. Otherwise, return an error statement.

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};

user_letter_input = input('Please enter the first letter of a word: ', 's');
user_num_input = input('Please enter how long you would like the word to be: ');

for i = words
    if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input))
        result = i;
    else
        result = 0;
    end
end

if (result == 0)
    disp('There are no matching words');
else
    disp(['Your new word is: ' result]);
end

The comparison returns i being 'apple' if I type a for the first input and 5 for the second input - as it should.

However, at the end when I try to see if (result == 0), it does not display the new word, even though result is not 0.

Could someone help me fix this please?

jape
  • 2,861
  • 2
  • 26
  • 58

3 Answers3

2

You are overwriting result each time through your for loop. The only time that result will be 0 after the loop, is if the last word in words matches your criteria.

I would recommend storing the matching words in a separate cell array, or have a boolean array to indicate which words match. In my opinion, using a boolean is better as it takes less memory and doesn't duplicate data.

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'};

user_letter_input = input('Please enter the first letter of a word: ', 's');
user_num_input = input('Please enter how long you would like the word to be: ');

isMatch = false(size(words));

for k = 1:numel(words)
    word = words{k};
    isMatch(k) = word(1) == lower(user_letter_input) && ...
                 numel(word) == user_num_input;
end

if ~any(isMatch)
    disp('There are no matching words');
else
    disp(['Your matching words are:', sprintf(' %s', words{isMatch})]);
end

Also, as a side note don't use the cell array in the for loop like that. That leads to a lot of confusion. Also avoid using i as a loop variable.

Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101
1

You're overwriting result each time the word in your dictionary doesn't match. The only time this will work is if the last word matches. You need to change both your initialization of result and your loop:

result = 0;   %// assume that no words match
for i = words
   if (....
      result = 1;   %// we found a match... record it
   end
   %// no else! If we get no match, result will already be 0
end
beaker
  • 16,331
  • 3
  • 32
  • 49
0

You can use a flag to detect whether a match was found:

breakflag = 0
for i = words
    if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input))
        breakflag = 1;
        break;
    end
end
if (breakflag == 0)
    disp('There are no matching words');
else
    disp(['Your new word is: ' i]);
end
neerad29
  • 463
  • 1
  • 3
  • 15