1

I have a question to the mapping of a matrix with another matrix which contains only 1 and 0. Here an example of my problem: A is the matrix with doubles

A = [ 1 4 3;
      2 3 4; 
      4 3 1; 
      4 5 5; 
      1 2 1];

B is a matrix with ones and zeros:

B = [ 0 0 0;
      0 0 0;
      1 1 1;
      1 1 1;
      0 0 0];

I want to achieve a matrix C which is the result of A mapped by B, just like that:

C = [ 0 0 0;
      0 0 0;
      4 3 1;
      4 5 5;
      0 0 0];

I tried B as a logical array and as a matrix. Both lead to the same error:

"Subscript indices must either be real positive integers or logicals."

chappjc
  • 30,359
  • 6
  • 75
  • 132
cacá
  • 85
  • 1
  • 5
  • Also see [this question](http://stackoverflow.com/questions/20054047/subscript-indices-must-either-be-real-positive-integers-or-logicals-generic-sol) for a [generic approach](http://stackoverflow.com/a/20054048/983722) to deal with this error. – Dennis Jaheruddin Mar 10 '14 at 10:32

2 Answers2

6

Just multiply A and B element-wise:

C = A.*B
Dan
  • 45,079
  • 17
  • 88
  • 157
1

I like Dan's solution, but this would be another way:

C = zeros(size(A));
C(B==1) = A(B==1);
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
tashuhka
  • 5,028
  • 4
  • 45
  • 64
  • this approach is also useful, especially for cells where the above operations do not work. Thank you! – cacá Feb 26 '14 at 14:49