Extract Submatrix with Logical Indexing Including Zeros
7 views (last 30 days)
Show older comments
Suppose I have a matrix A and a logical matrix B
A = [1:3 ; 1:3 ; 1:3];
B = [1 0 0 ; 0 1 0 ; 0 0 1];
B = logical(B);
I want to create a new matrix by indexing matrix A with logical B, so that I can achieve something this
[1 0 0 ; 0 2 0 ; 0 0 3]
However when I use A(B), I only get a vertical array with the three extracted numbers. I want the original 3 by 3 matrix A containing only the integers that correspond to the 1's of matrix B, while assigning the rest of matrix A as zero.
0 Comments
Accepted Answer
Fangjun Jiang
on 12 Feb 2016
Edited: Fangjun Jiang
on 12 Feb 2016
C=A.*B
Or, if insisting on "logical indexing"
D=zeros(size(A))
D(B)=A(B)
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!