Create variable array and assign values simultaneously

36 次查看(过去 30 天)
I have dozens of unrelated variables that I want to assign values to at the same time. For example, my variable names are: Adam, Beth, Cody, Drew, Emma, Fran, Glen, Hugo. And I have an array of grades: g = [8 7 6 5 4 3 2 1];
I want to assign:
Adam = 8;
Beth = 7;
...
Hugo = 1;.
One way I have seen something similar is with the deal() command. so I could execute:
grades = num2cell(g);
[Adam, Beth, Cody, Drew, Emma, Fran, Glen, Hugo]=deal(g{:});
This would work fine. Except in my case, I don't just have 8 names... I have a hundred. I would like to create some sort of "Variable array" such that:
Names = [Adam, Beth, Cody ... etc];
and I could simply assign:
grades = num2cell(g);
[Names]=deal(g{:});
Can someone help me with the correct way to do this?
  1 个评论
Stephen23
Stephen23 2017-5-24
"Can someone help me with the correct way to do this?"
The correct way is to NOT do this.
Magically creating or accessing variable names is a really bad way to write code, which is explained in the MATLAB documentation, because that code will be "...less efficient and more difficult to read and debug than code that uses other functions or language constructs"
For whatever reason, some beginners imagine that dynamically creating or accessing variable names will solve all of their problems. It will not: it will actually make your code slow, buggy, hard to debug, hard to read, and pointlessly complicated:
Much simpler is to use indexing, which is trivially easy and very fast, a table, or dynamic fieldnames in a structure.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2017-5-24
The correct way is not to do that.
Names = {'Adam', 'Beth', 'Cody' ... etc};
data_struct = cell2struct( num2cell(g), Names, 2 );
or
data_table = array2table(g(:), 'VariableNames', {'grade'}, 'RowNames', Names);

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by