Getting the Original Variable Name from a Concatenated Matrix

I'm working on a personal project and I've kinda hit a wall. I made many variables that have a values that make a 1x5 vector. Ultimately, I want to make a matrix with these variables (so if I put 13 of these variables, the end matrix will be a 13x5). That part isn't the problem.
What I am having trouble with is that I want the user to be able to see the individual variables in the matrix based on their corresponding values.
Here's an example:
Bob = [5 9]
Joe = [6 0]
Sue = [5 6]
Mary = [6 1]
Bill = [4 8]
Names = [Bob;Joe;Sue;Mary;Bill]
...So Names is a 5x2 matrix with the VALUES of each of the variables. What I want is some way to reverse this process, some way to be able to get the original variable name from the Names matrix. If possible, I would like to take this a step further and possibly get to a point where if I, say, type Names(1,:), I get "Bob" rather than [5 9].
Of further note, all the variables that I am using have a unique vector value so that it could be specifically denoted by the specific value.

回答(1 个)

The easiest solution is to not confuse data with the abstract representation of it, the variables. Here are two ways youc an do that.
Method One: Cell Array and Numeric Array
Keep your names in a cell array, and the data in a numeric array, then the whole task becomes trivial:
>> myName = {'Bob','Joe','Sue','Mary','Bill'};
>> myData = [5,9;6,0;5,6;6,1;4,8];
>> myName{2}
ans = Joe
>> myData(2,:)
ans =
6 0
And of course it is possible to look up either the names or the rows of data to locate them in the other array:
>> X = strcmp('Joe',myName);
>> myData(X,:)
ans =
6 0
Method Two: Structure Another solution would be to use a structure:
>> data.Bob = [5,9];
>> data.Joe = [6,0];
>> data.Sue = [5,6];
>> data.Mary = [6,1];
>> data.Bill = [4,8];
>> data.Joe
ans =
6 0
>> data.('Sue')
ans =
5 6
>> fieldnames(data)
ans = {'Bob','Joe','Sue','Mary','Bill'}
There are lots of easy ways of accessing structure data:
including using dynamic filed names:
Summary
Beginners often confuse data with variables: a variable should not be named using data, because this makes the processing more complicated. It makes your own code simpler and more abstracted when these concepts are kept separated. Read this for an explanation of why you should not include data in your variable names:

类别

在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息

产品

标签

尚未输入任何标签。

提问:

2015-10-17

编辑:

2015-10-17

Community Treasure Hunt

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

Start Hunting!

Translated by