Search code examples
matlabrecode

Reverse coding in matlab


I have a survey data in matlab and I have some reverse coded items. All I need is to do reverse coding in certain questions.I was using this code reversecoding = myStruct.mysurvey(:,4) == 5 ; mySturct.mysurvey(reversecoding,4) = 3 ; but I realized I will probably have some issues by using this.

For example when I recode the value of 3 to 5;

 myStruct.mysurvey=
  3     3     3     3
  6     6     6     6
  3     3     3     3
  7     6     6     7
  4     3     5     5 <--
  5     5     4     5 <--
       ...

reversecoding = myStruct.mysurvey(:,4) == 5 ;
   mySturct.mysurvey(reversecoding,4) = 3 

%after (the last 2 values has recoded to 3)


 myStruct.mysurvey=
  3     3     3     3
  6     6     6     6
  3     3     3     3
  7     6     6     7
  4     3     5     3 <--
  5     5     4     3 <--
       ...

But after that, when I am recoding the 3 to 5 it recodes my all 3s (including the ones that I just recoded from 5) to 5.

To exemplify;

    %after I recode 3s to 5

 myStruct.mysurvey=
  3     3     3     3
  6     6     6     6
  3     3     3     3
  7     6     6     7
  4     3     5     3 <--
  5     5     4     3 <--
       ...

     reversecoding = myStruct.mysurvey(:,4) == 3 ;
   mySturct.mysurvey(reversecoding,4) = 5 ;

myStruct.mysurvey= 3 3 3 5 6 6 6 6 3 3 3 5 7 6 6 7 4 3 5 5 <-- 5 5 4 5 <-- %they are 5 again ... %again the last two values of column 4 goes back to 5...

How can I get rid of this problem? This is the code;

reversecoding = myStruct.mysurvey(:,4) == 5 ;
   mySturct.mysurvey(reversecoding,4) = 3 ;
% after
 reversecoding = myStruct.mysurvey(:,4) == 3 ;
   mySturct.mysurvey(reversecoding,4) = 5 ;
 % all other values will be transformed.
 %old 1 will be 7
 %old 2 will be 6
      ...
 %old 6 will be 2
 %old 7 will be 1

What is the best way to recode them? I will be recoding from 1 to 7.


Solution

  • You can use a container map to create the mapping from old to new values. This is quite simple:

    map = containers.Map(old_values, new_values);
    

    or in your case

    map = containers.Map(1:10, 10:-1:1);
    

    you can then use map to map an old value to its corresponding new value like this:

    >> map(1)
    ans =
        10
    >> map(4)
    ans =
         7
    

    Note that you can only "call" map on single values, and not on arrays. But you can use e.g. arrayfun to simplify this to one call:

    >> myStruct.mysurvey(:, 4) = [9, 2, 1, 10, 4];    % Example data
    >> myStruct.mysurvey(:, 4)
    ans =
         9
         2
         1
        10
         4
    
    >> myStruct.mysurvey(:, 4) = arrayfun(@(x) map(x), myStruct.mysurvey(:, 4));
    >> myStruct.mysurvey(:, 4)
    ans =
         2
         9
        10
         1
         7