B Bo
B Bo

Reputation: 1

Find the first vowel in a word

Please write a Matlab function to find the first vowel in a word, and test the program using your name as the input.

The function header is function v = findfirstvowel (word)

My work is :

function v = findfirstvowel (word)
   vow = 'aeiouAEIOU';
   for i=1:size(word)
       for j=1:10
           if word(i)==vow(j)
               v=word(i);
               break;
           end
       end
    end

I don't know why but I didn't work

Upvotes: 0

Views: 562

Answers (1)

Suever
Suever

Reputation: 65460

The break only breaks out of the innermost for loop.

From the documentation:

In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

If you want to exit the function, you'd want to use return instead.

function v = findfirstvowel (word)
   vow = 'aeiouAEIOU';
   for i=1:size(word)
       for j=1:10
           if word(i)==vow(j)
               v=word(i);
               return;
           end
       end
    end

Instead of the double for loop, you'd be much better off using something like ismember to check to find the vowels and use find to return the index of the first one. Also you can convert the word to lowercase and only compare to 'aeiou'.

function v = findfirstvowel (word)
    isvowel = ismember(lower(word), 'aeiou');
    v = word(find(isvowel, 1, 'first'));
end

If you wanted the other vowels using this approach you could do the following.

isvowel = ismember(lower(word), 'aeiou');
vowels = word(isvowel);

first_vowel = vowels(1);
second_vowel = vowels(2);

Upvotes: 1

Related Questions