Calling variables instead of values

12 views (last 30 days)
Will
Will on 31 Oct 2011
I had previously asked this: http://www.mathworks.com/matlabcentral/answers/19875-calling-variables-instead-of-values And marked as answered, but I have a little hiccup.
I have this:
A=6; B=7; C=5;
x = [7 5 6]
I want to call x1 as:
x1 =
B C A
Previous answered:
x = [2 3 1]
xc = {'A' 'B' 'C'}
x1 = xc(x)
This line of code only works for values that are within the number of columns of the matrix.

Accepted Answer

Alex
Alex on 31 Oct 2011
In the previous question you have a single set (x) that has several elements that you want to link to.
In the new problem, you do not have a single set, so you have a way to search each of the possible solutions. There is no easy way to do this. The two ways I know how to do this is with if/else tree (messy), or an enumerator and switch/case setup (not as messy).
if/else tree example
for i = 1:3
if(x(i) == A)
x1(i) = 'A';
elseif( x(i) == B)
...
...
end
end
The other option is using enumeration and switch/case. I've only used enumeration in older versions, so the following is a quick setup for 2009 A.
classdeff my_letters (Enumeration) < int32
proerties
A = 6;
B = 7;
C = 8;
end
methods (static)
function str = string(input)
switch int32(input)
case my_letter.A
str = 'A';
...
...
...
end
end
Now you can use a switch case as opposed to an if-else tree
Switch x(i)
case int32(my_letters.A)
X1(i) = my_letters.A.string();
...
...
end
The switch/Case is cleaner and faster code wise.
  2 Comments
Will
Will on 31 Oct 2011
Thank you very much. I had not done much reading on 1-to-1 and 1-to-many analyses. Very helpful, thank you.
Andrei Bobrov
Andrei Bobrov on 31 Oct 2011
S = {'A' 'B' 'C'}
C =[6 7 5]
x = [7 5 6]
[loc,loc] = ismember(x,C)
out = S(loc)

Sign in to comment.

More Answers (1)

Alex
Alex on 31 Oct 2011
My original comment about one-to-one, I realize, is not the best descriptor.
I've since edited the original post to reflect that and I'll try to explain the differences a little better.
In your original question, you have a base set (x) and you are looking to match values within that set. Since all the values are contained within a single set, this is easy.
In the new question, there are multiple sets (A, B, & C) that all have to be searched since each one could possibly contain the solution that you desire.
If there is a way to combine the multiple sets (like Will's above comment) into a single set (set S in Will's example), then the solution can be achieved much easier. Otherwise, the if/else tree or the switch/case ideas I mentioned are the best options, that I know of.

Community Treasure Hunt

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

Start Hunting!