Passing multiple variables to function in 1 input

18 views (last 30 days)
Is there any way to pass multiple variables in a single structure/cell/vector/whatever to a function, so that I can avoid writing out all variables and call variables within function shortly by their names (rather than eg. structureName.variableName)?
In other words, instead of this:
a=1;
b=2;
c=3;
...
z=24;
myFun(a, b, c, ..., z)
(and inside my function:)
function myFun(a, b, c, ..., z)
newVal = c % calling variable shortly by its name
I would like to have something like:
alphabet = struct('a', 1, 'b', 2, 'c', 3, ..., 'z', 24);
myFun(alphabet)
(and inside my function:)
function myFun(alphabet)
newVal = c % calling variable shortly by its name
  3 Comments
Maciej Grybko
Maciej Grybko on 4 Nov 2018
Or maybe saving workspace and loading it at the beginning of every function?
Stephen23
Stephen23 on 5 Nov 2018
"Or should I use global variables instead?"
No.
Global variables are one way that beginners force themselves into writing slow, complex, buggy code.

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 4 Nov 2018
Edited: Walter Roberson on 4 Nov 2018
  1 Comment
Maciej Grybko
Maciej Grybko on 4 Nov 2018
Thanks. I checked couple of links. For me the best solution is structure array.
a = 1;
b = 24;
c = 349;
d = 0.07;
mydata = struct('f', {a, b, c, d})
[a, b, c, d] = mydata.f

Sign in to comment.

More Answers (2)

Matt J
Matt J on 5 Nov 2018
Edited: Matt J on 5 Nov 2018
See my STRUCTVARS FEX tool for unpacking lots of structure fields to separate variables.
  1 Comment
Maciej Grybko
Maciej Grybko on 6 Nov 2018
Thanks Matt. That's what I was looking for. However, I figured out that the same is possible with MATLAB built-in structure arrays.
a = 1;
b = 24;
c = 349;
d = 0.07;
mydata = struct('f', {a, b, c, d})
[a, b, c, d] = mydata.f

Sign in to comment.


Matt J
Matt J on 5 Nov 2018
If your variables really are just a long list of scalars, like in your posted example, you should be using vectors to carry them around, e.g.,
X=[a,b,c,d,...,z];
function myFun(X)
newVal = X(3)

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!