Replacing Variables using the switch/case function.

3 views (last 30 days)
Okay so I have a vector saved as a variable of a bunch of numbers... Ex: X=(3 5 4 7 8 6 5 6 7 9 5 4)
If I have a list of conversions for these variables like, 3=.1, 4=.2, 5=.3, 6=.55, 7=.8, 8=1.25, 9=1.7, How can I switch out the values in this vector to each of these options, my original vector has about 70 values ranging from 3:9. How can the switch function be used for this replacement?

Answers (3)

Stephen23
Stephen23 on 12 Mar 2015
Edited: Stephen23 on 12 Mar 2015
The easiest and fastest way would be to treat the values of X as indices, and simply define a look-up vector like this:
>> A(3:9) = [0.1,0.2,0.3,0.55,0.8,1.25,1.7];
which you can use with your X vector very simply as indices:
>> X = [3,5,4,7,8,6,5,6,7,9,5,4];
>> A(X)
ans = 0.1 0.3 0.2 0.8 1.25 0.55 0.3 0.55 0.8 1.7 0.3 0.2
Or equivalently but written more explicitly:
>> key = [3, 4, 5, 6, 7, 8, 9];
>> val = [0.1,0.2,0.3,0.55,0.8,1.25,1.7]
>> A(key) = val;
>> A(X)
This code places the values in val in the new vector A, in positions given by key. We can them simply use A(X) to get the values in A corresponding to the values/indices in X (this is called indexing, and is a very powerful part of MATLAB).
This method will work as long as all values in X are integer and are greater than zero.
Note that your example code uses parentheses to define the vector: in MATLAB, a vector like this is created by concatenating values using square brackets. Note that the square brackets are not a list operator, but a concatenation operator!
  2 Comments
Guillaume
Guillaume on 12 Mar 2015
This method will work as long as all values in X are integer and are greater than zero.
... and not too big, since it creates a vector of size 1 x max(X).
Stephen23
Stephen23 on 12 Mar 2015
Edited: Stephen23 on 12 Mar 2015
As the OP states clearly that X has "values ranging from 3:9", then A should have length nine.

Sign in to comment.


Guillaume
Guillaume on 12 Mar 2015
Stephen's answer (create a look-up table) is the best for a reasonably small number of integer look-up values all within the same range.
Alternatively, for an arbitrary range and type of look-up value, you can use a map
>>m = containers.Map([3:9 -1.4], [0.1 0.2 0.3 0.55 0.8 1.25 1.7 2.5]);
>>X = [3 5 4 7 8 6 5 6 7 9 5 4];
>>cell2mat(values(m, num2cell(X)) %unfortunately the interface is a bit awkward for vectors
ans = 0.1 0.3 0.2 0.8 1.25 0.55 0.3 0.55 0.8 1.7 0.3 0.2
>>m(-1.4)
ans = 2.5

Jan
Jan on 12 Mar 2015
X = [3 5 4 7 8 6 5 6 7 9 5 4];
L = 3:9;
V = [0.1,0.2,0.3,0.55,0.8,1.25,1.7];
[ex, pos] = ismember(X, L);
Result = V(pos);

Community Treasure Hunt

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

Start Hunting!