Replacing Variables using the switch/case function.
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposte (3)
Stephen23
il 12 Mar 2015
Modificato: Stephen23
il 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 Commenti
Guillaume
il 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).
Guillaume
il 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.
>>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
0 Commenti
Jan
il 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);
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical 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!