Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple elements from a vector in Matlab?

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!

like image 901
FF0605 Avatar asked Dec 19 '22 21:12

FF0605


1 Answers

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.

like image 200
sebastian Avatar answered Jan 05 '23 08:01

sebastian