Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function with an argument which is an array?

Tags:

matlab

I need to declare a function that has 32 arguments, so it would be handy to put an unique argument: an array of 32 elements. I don't find the syntax to do that, I've tried everythinh like: function x=myfunction(str(32)) (etc...) But without success.

like image 694
Ramy Al Zuhouri Avatar asked Feb 22 '23 18:02

Ramy Al Zuhouri


2 Answers

Unlike other languages, MATLAB can accept matrices as a single argument; so you could just check that the input argument is a vector of length 32:

function x = myfunction(arg)
    if length(arg) ~= 32
        error('Must supply 32 arguments!');
    end

    %# your code here
end

If it's a variable number of arguments, check out varargin:

function x = myfunction(varargin)

But for 32 arguments, consider using an input structure:

function x = myfunction(argStruct)

    if length(fieldnames(argStruct)) ~= 32
        error('not enough arguments!');
    end

Supply arguments in the structure, then pass the structure:

>> myArgs = struct();
>> myArgs.arg1 = 5;
>> myArgs.arg2 = 7;
>> %#(etc)
>> x = myfunction(myArgs);

Then in the function, you could either call argStruct.arg1, etc, directly; or unpack it into 32 different variables inside the function. I would give the fields descriptive names so you don't refer to them as arg1, etc inside your function. For that many input arguments, people using the function probably won't remember the order in which your function requires them to pass inputs to. Doing it with a struct lets users pass in arguments without needing to think about what order those inputs are defined.

like image 129
Dang Khoa Avatar answered Feb 25 '23 09:02

Dang Khoa


To add to @strictlyrude27's awesome answer, it looks like you may misunderstand how function declarations work in Matlab. You wrote:

function x=myfunction(str(32))

However, you don't need to declare the type of input in matlab. Just give it a name, and then use it. So, the proper syntax for a declaration would be:

function x = myfunction(myInput)
like image 20
user670416 Avatar answered Feb 25 '23 09:02

user670416