NESHOM
NESHOM

Reputation: 929

Matlab function with many inputs of different types

What is the best way of passing several (more than 20) variables of different types and size to a function?

These variables are of types number, string, vector, matrix and cell.

Currently this is the way I am dealing with it:

% BEGIN main m-file
...
parameter1=
parameter2=
.
.
.
Func1
% END main m-file

my function:

function Func1
parameter1=evalin('base','parameter1');
parameter2=evalin('base','parameter2');
.
.
.

% do something

end

I am wondering if there is a better approach for this? Thank you

Upvotes: 1

Views: 134

Answers (1)

Bas Swinckels
Bas Swinckels

Reputation: 18488

I prefer to use structs when passing large amounts of parameters to a function. If you have a large number of regular parameters, it might be better to use a vector or cell array, but for mixed parameters structures are more convenient, and you can give the field-names useful names:

options.gain = 5.432;
options.offset = 1.23;
options.title = 'Just a straight line';
options.matrix = [1, 2; 3, 4];

And you would define your function like this:

function do_something(options, x)
y = options.gain * x + options.offset;
plot(x, y)
title(options.title)

Upvotes: 3

Related Questions