1
votes

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."

2
Also see this question for a generic approach to deal with this error.Dennis Jaheruddin

2 Answers

6
votes

Just multiply A and B element-wise:

C = A.*B
1
votes

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

C = zeros(size(A));
C(B==1) = A(B==1);