0

I'm writing a function in Matlab that prompts the user to select an Instrument (.wav file) to be read in using the wavread function.

I'm trying to include some sort of error handling/deal with incorrect inputs from the user.

So far my function looks like this:

prompt = 'Select Instrument, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
str = input(prompt,'s');
if isempty(str)
    str = 't';
end

while(str ~= 'P') || (str ~= 'F') || (str ~= 'V') || (str ~= 'G')
    prompt = 'Invalid Selection! Choose, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
    str = input(prompt,'s');
    if isempty(str)
        str = 't';
    elseif (str == 'P') || (str == 'F') || (str == 'V') || (str == 'G')
        break
    end
end

If prompted during the while loop, it successfully prompts the user and reads in the .wav, but if the user presses P,F,V, or G on the first prompt, the while loop is still used and "Invalid Sel... " is still displayed...

I'm not sure how I should be implementing this....

2 Answers 2

3

that's because you logic is wrong

(str ~= 'P') || (str ~= 'F') || (str ~= 'V') || (str ~= 'G')

is always true as str is always going to be different from either P, F, V or G. It can't be the same as all of them which is what you are asking.

It should be

str ~= 'P' && str ~= 'F' && str ~= 'V' && str ~= 'G'

or

~(str == 'P' || str == 'F' || str == 'V' || str == 'G')

or in sane matlab

~any('PFVG' == str)
Sign up to request clarification or add additional context in comments.

1 Comment

Oh of course. I feel silly now. Thanks for clearing that up. Problem solved :D Also ~any('PFVG' == str) is a really cool line of code, I'm going to use this. Thanks for your time.
1

how about using strcmp?

str = input(prompt,'s');
if isempty(str)
    str = 't';
end

while ~any(strcmp(str,{'P' 'F' 'V' 'G'})) %|| (str ~= 'F') || (str ~= 'V') || (str ~= 'G')
    prompt = 'Invalid Selection! Choose, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
    str = input(prompt,'s');
    if isempty(str)
        str = 't';
    elseif (str == 'P') || (str == 'F') || (str == 'V') || (str == 'G')
        break
    end
end

1 Comment

I've not seen the strcmp before. I'm going to have a read up of it now. Thanks for you time :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.