Passing multiple variables to function in 1 input

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

Maciej Grybko
Maciej Grybko 2018년 11월 4일
편집: Maciej Grybko 2018년 11월 4일
I want to improve clarity of my program. I have 20+ functions and majority of their inputs are the same. Can I store them in 1 object? Or should I use global variables instead?
Or maybe saving workspace and loading it at the beginning of every function?
"Or should I use global variables instead?"
No.
Global variables are one way that beginners force themselves into writing slow, complex, buggy code.

댓글을 달려면 로그인하십시오.

 채택된 답변

madhan ravi
madhan ravi 2018년 11월 4일
편집: Walter Roberson 2018년 11월 4일

0 개 추천

댓글 수: 1

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

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Matt J
Matt J 2018년 11월 5일
편집: Matt J 2018년 11월 5일

0 개 추천

See my STRUCTVARS FEX tool for unpacking lots of structure fields to separate variables.

댓글 수: 1

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

댓글을 달려면 로그인하십시오.

Matt J
Matt J 2018년 11월 5일
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)

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

질문:

2018년 11월 4일

댓글:

2018년 11월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by