e.g
I have a vector:
a=[4 4 15 15 9 9 7 7];
how do I efficiently replace all 4s into 1s, all 15s into 2s, 9s into 3s and 7s into 4s? instead of coding repeatly:
a(a==4)=1; a(a==15)=2; a(a==9)=3; a(a==7)=4; ....
in the case I have too many number to be replaced?
Thank you very much!
If you really want an "abitrary" replacement, where there's no direct relation between original and replaced value, you could use ismember
:
>> map = [4 1; 15 2; 9 3; 7 4];
>> [~, loc] = ismember(a, map(:,1));
>> a(:) = map(loc,2)
a =
1 1 2 2 3 3 4 4
Depending on what your larger context is, you might want to check unique
, as it seems your doing something similar. In this case for example:
>> [~,~,a2] = unique(a, 'stable')
a2 =
1 1 2 2 3 3 4 4
Which works for your example and doesn't require you to construct a map as it makes it's own based on order of appearance.
Or if your version of Matlab predates the 'stable'
property of unique` then
>> [~,~,a2] = unique(a)
a2 =
1 1 4 4 3 3 2 2
Which is similar to your replacement, though these numbers refer to the index of each element in the sorted list of distinct elements in a
, while your example seems to use the unsorted index - though this might just be an arbitrary choice for your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With