1

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

3
  • What kind of size are your vectors and matrices ? Commented Jan 25, 2015 at 15:20
  • Cell Array, i guess. There are plenty of examples with it on SO. Commented Jan 25, 2015 at 15:38
  • 1X2 and 2X3 usually! Commented Jan 25, 2015 at 15:39

1 Answer 1

3

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)
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.