Tomáš Zato
Tomáš Zato

Reputation: 53139

How can I make overloaded function that accepts both matrix and individual parameters?

As a homework given by my Robotics subject, I'm supposed to make functions that convert between coordinate systems. Specifically we are supposed to do this:

Function parameters are Xo = mySYSTEM1toSYSTEM2(Xi), where: Xi is matrix 3 * N. Every column presents one point, elements of the column are then the coordinates of that point in SYSTEM1.

I know the equations for conversion but I need help with matlab syntax. I was imagining something like this:

%Takes matrix as arguments
% - loops through it and calls mySphericToCarthesian(alpha, beta, ro) for every column
function [Xo] mySphericToCarthesian[Xi]
%Converts one spheric point to another
function [x, y, z] mySphericToCarthesian[alpha, beta, ro]

Matlab doesn't seem to like this.

How can I establish these two function so that I can actually start with the homework itself?

Upvotes: 0

Views: 989

Answers (1)

LowPolyCorgi
LowPolyCorgi

Reputation: 5169

Well, probably the simplest option would be to define two different functions. In Matlab, function overloading shadows all functions but one (i.e. only one function with a given name can be used at a time), which is not very interesting in practice.

However, if you absolutely want only one function with two different behaviors, then it can be achieved by using the nargin and nargout variables. Inside a function, they indicate the number of inputs and outputs specified by the calling script/function. You can also use varargin, which places all the inputs in a cell.

In practice, this gives:

function [x, y, z] = mySphericToCarthesian(varargin)
% Put your function description here.

switch nargin
    case 1

        Xi = varargin{1};

        % Do you computation with matrix Xi
        % Define only x, which will be used as the only output

    case 3

        alpha = varargin{1};
        beta = varargin{2};
        rho = varargin{3};

        % Do you computation with alpha, beta and rho
        % Define x, y and z for the outputs

 end

Upvotes: 2

Related Questions