0

I'm wondering how to write a function in Matlab with two different ways of passing the same input.

One example of this is the built-in function lsqcurvefit. You can either pass the input like this:

x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)

where the first 4 arguments are required and the last 3 are optional, OR you can call it like this:

x = lsqcurvefit(problem)

where problem is a struct containing the same inputs. In this case there is only one required input.

My question is: how do I write a function that can take the same input in two different ways?

I looked at documentation and can't seem to find it because I just don't know what words or terminology to search for... Can someone point me to this? I'm sure it's very simple. Maybe it's trivial and I'm just missing it?

Ben

EDIT: It seems what I may have been looking for is 'function overloading' and 'function signature'.

6
  • vargin and nargin is the keyword. Commented Nov 15, 2017 at 12:58
  • @OmG Ok, let's push this idea just for fun. What if I want to pass an input in two different ways, but both ways involve passing a single struct with different internal structure. Then nargin will tell me I have one input and I will be unable to differentiate the type. Is there a way to do it then? Commented Nov 15, 2017 at 13:04
  • I feel like nargin and varargin are a poor way to change function behaviour in general. I shouldn't need to rely on the number of inputs to change behaviour. After the reply below, I now know I'm looking for something more akin to "function overloading". Commented Nov 15, 2017 at 13:42
  • See this post for more info: stackoverflow.com/a/7217820/3768871 Commented Nov 15, 2017 at 13:45
  • 1
    Possible duplicate of Overloading functions Commented Nov 15, 2017 at 15:14

1 Answer 1

-3

I am not sure on how to write code on matlab but I believe that the concept is the same for all programming languages so " just do method overriding where by one method will passes 4 parameters and other pass 2. e.g

//assume that the  following method are defined within the class

public void FirstFunction( int x, int y,int c,int f){
    System.out.print(x + y + c + f);
}

public void SecondFunction( int m,int s){
    System.out.print(m - s);
}

//within the main method on java you call these method
//so it will depend on the number of parameters you have passed the it will call. 
Sign up to request clarification or add additional context in comments.

1 Comment

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.