3

I want to right a code in MATLAB which calculates a given formula, and I want to write the code with the same notation as in the given formula. In the formula I have two different functions with the same name but that only differ in the number of the arguments: Kn(a,b) and Kn(a).

Is there a way in MATLAB to define overloading functions like in c++?

1
  • Yes, call the function by the same name and put it at a higher position in your path. Commented Oct 18, 2015 at 9:21

1 Answer 1

10

If you want to define two functions of the same name with a different number of input arguments, you should define them in the same function file and use varargin/nargin to treat the two cases:

function out=Kn(varargin)

if nargin==1
  a=varargin{1};
  %
  %here do what Kn(a) does
  %
  %out=...
elseif nargin==2
  a=varargin{1};
  b=varargin{2};
  %
  %here do what Kn(a,b) does
  %
  %out=...
else
  error('Kn accepts up to 2 input arguments!')
end

%or maybe here do what both Kn(a) and Kn(a,b) do after some initial differences
%and return 'out' here

If the two cases are similar then this is not confusing, nor cumbersome; and if the two functions are very different than you should seriously consider using separate functions with separate names. While in paper-based scientific computations you can easily distinguish between quantities based on the number of indices, this can be very confusing in programming (and I would advise against it even if it was possible to do in matlab).

Sign up to request clarification or add additional context in comments.

Comments

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.