map a matrix with another matrix

2020-04-18 09:04发布

问题:

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

回答1:

Just multiply A and B element-wise:

C = A.*B


回答2:

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

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