4

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.

2 Answers 2

5

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.

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

Comments

3

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)

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.