2

I'm trying to check the input of a Matlab function to see whether the user has forgotten about it or not (which is easy to do in this case).

If the user has not supplied number_obs then I want to pause the program and wait for the user to input this information.

Some other StackOverflow posts seem to suggest using ~exist however this doesn't seem to work. Can anybody suggest what I'm doing wrong here?

function output=test(number_obs) 
if ~exist('number_obs'),
    number_obs=input('How many observations do you have in your experiments?')
end 

The Python equivalent would be something like:

def test(number_obs):
    if nummber_obs != None:
        output=raw_input('How many observations do you have in your experiments? :')
    return output
4
  • 1
    Your Python code does not work correctly, as the number_obs does not have a default value. Commented Jan 14, 2016 at 11:46
  • What is not working? Asking for an input when you already passed it or the opposite case? Commented Jan 14, 2016 at 13:43
  • What do you mean by "this doesn't seem to work"? The MATLAB version works flawlessly. Commented Jan 14, 2016 at 13:59
  • 1
    Your code works fine for me, MATLAB R2014b Commented Jan 14, 2016 at 14:12

2 Answers 2

6

You can do this with nargin

function output=test(number_obs) 
if nargin<1
    number_obs=input('How many observations do you have in your experiments?')
end 
Sign up to request clarification or add additional context in comments.

Comments

2

(Edited to correct the truth) It may not matter here, but to be on the safe side, you should always specify the type of object you're checking. In your case, its a 'var', so

if ~exist('number_obs','var'),

Thanks to dasdingonesin for pointing this out.

2 Comments

It doesn't need to. The second argument is optional (see de.mathworks.com/help/matlab/ref/exist.html).
@dasdingonesin I plead guilty to not reading up-to-date help files.

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.