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'.

Ben
  • 213
  • 1
  • 7
  • `vargin` and `nargin` is the keyword. – OmG Nov 15 '17 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? – Ben Nov 15 '17 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". – Ben Nov 15 '17 at 13:42
  • See this post for more info: https://stackoverflow.com/a/7217820/3768871 – OmG Nov 15 '17 at 13:45
  • `lsqcurvefit` probably just checks the class of the first input variable to see if it's a function handle or a structure and unpacks as necessary. – sco1 Nov 15 '17 at 15:05
  • 1
    Possible duplicate of [Overloading functions](https://stackoverflow.com/questions/8630889/overloading-functions) – sco1 Nov 15 '17 at 15:14

1 Answers1

-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. 
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • Please see: https://meta.stackoverflow.com/questions/290046/if-the-question-is-specifically-about-a-certain-language-is-an-answer-in-anothe – sco1 Nov 15 '17 at 14:42