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
2018 年 11 月 4 日
編集済み: Maciej Grybko
2018 年 11 月 4 日
Maciej Grybko
2018 年 11 月 4 日
Stephen23
2018 年 11 月 5 日
"Or should I use global variables instead?"
No.
Global variables are one way that beginners force themselves into writing slow, complex, buggy code.
採用された回答
その他の回答 (2 件)
1 件のコメント
Maciej Grybko
2018 年 11 月 6 日
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 についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!