Create variable array and assign values simultaneously

36 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 24 Mag 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.

Accedi per commentare.

Risposte (1)

Walter Roberson
Walter Roberson il 24 Mag 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);

Categorie

Scopri di più su Operators and Elementary Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by