jape
jape

Reputation: 2901

Compare first letter of strings in Matlab

I would like to see if the letter inputted by the user matches any of the words in a dictionary.

Could someone please help me do this? Thank you!

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

user_letter_input = input('Please enter the first letter of a word: ');

for i = words
    if (i starts with user_letter_input)
        disp(['Your new word is: ' i]);
    end
end

Upvotes: 0

Views: 327

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112669

Here's a different, admittedly more hackish approach:

w = char(words); %// convert to 2D char array, padding with spaces
result = find(w(:,1)==user_letter_input); %// test equality with first column

result will be a vector with the indices of all matching words. For example,

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

will give

result =
     2
     3

Upvotes: 0

neerad29
neerad29

Reputation: 473

You can use:

if(i{1}(1) == user_letter_input)

Upvotes: 2

Related Questions