3

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!

Vasilije Bursac
  • 185
  • 1
  • 2
  • 15

1 Answers1

4

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
Alec
  • 4,235
  • 1
  • 34
  • 46
  • 2
    Thank you very much for detailed answer! This solved my problem and I learned something new, too... I wish you all the best! – Vasilije Bursac Oct 28 '19 at 01:24
  • 1
    You can do it more easily than that, you could just write: `x[I(3)] .= 0`. Another way that doesn't use logical indices is with `diagind` from the LinearAlgebra stdlib: `x[diagind(x)] .= 0`. – DNF Oct 28 '19 at 11:05
  • @DNF - Thanks - for the particular example I used (`reshape(1:9,3,3)`), I would have had to `collect` the range into an array which was an extra step. But for many arrays the direct indexing would work with no extra effort needed. – Alec Oct 28 '19 at 19:47