Julia equivalent of Matlab's “logical” matrix

Viewed 416

Is there Julia equivalent for Matlab's “logical” matrix which you can use to mark certain positions in matrix and then use it for matrix manipulation?

In matlab it looks like this:

A=magic(3);
C=eye(size(A));
C=logical(C);
M=A;
M(C)=0;

I need to keep zeros on main diagonal. In matlab I would do it like this, but in Julia there is no "logical" matrix. I searched for Julia equivalent but i couldn't find anything. Thanks in advance!

1 Answers

You can create a BitArray or an Array of Bools, which are for most intents and purposes the same.

E.g.

> using LinearAlgebra

>I(3)                            # `I()` is the identity matrix function 
3×3 Diagonal{Bool,Array{Bool,1}}:
 1  ⋅  ⋅
 ⋅  1  ⋅
 ⋅  ⋅  1

And you can use it to zero out elements in another matrix by broadcasting the logical not operator ~, and then multiplying each element in the other matrix (by broadcasting * with .*).

For example:

> x = reshape(1:9,3,3)
 1  4  7
 2  5  8
 3  6  9

> x .* .~I(3)
 0  4  7
 2  0  8
 3  6  0
Related