Create variable array and assign values simultaneously

36 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 24 May 2017
"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.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 24 May 2017
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);

Categories

Find more on Operators and Elementary Operations 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!