MATLAB supports the use of logical masking in order to perform selection on a matrix without the use of for loops or if statements.

A logical mask is defined as a matrix composed of only `1`

and `0`

.

For example:

```
mask = [1 0 0; 0 1 0; 0 0 1];
```

is a logical matrix representing the identity matrix.

We can generate a logical mask using a predicate to query a matrix.

```
A = [1 2 3; 4 5 6; 7 8 9];
B = A > 4;
```

We first create a 3x3 matrix, `A`

, containing the numbers 1 through 9. We then query `A`

for values that are greater than 4 and store the result in a new matrix called `B`

.

`B`

is a logical matrix of the form:

```
B = [0 0 0
0 1 1
1 1 1]
```

Or `1`

when the predicate `A > 4`

was true. And `0`

when it was false.

We can use logical matrices to access elements of a matrix. If a logical matrix is used to select elements, indices where a `1`

appear in the logical matrix will be selected in the matrix you are selecting from.

Using the same `B`

from above, we could do the following:

```
C = [0 0 0; 0 0 0; 0 0 0];
C(B) = 5;
```

This would select all of the elements of `C`

where `B`

has a `1`

in that index. Those indices in `C`

are then set to `5`

.

Our `C`

now looks like:

```
C = [0 0 0
0 5 5
5 5 5]
```

We can reduce complicated code blocks containing `if`

and `for`

by using logical masks.

Take the non-vectorized code:

```
A = [1 3 5; 7 9 11; 11 9 7];
for j = 1:length(A)
if A(j) > 5
A(j) = A(j) - 2;
end
end
```

This can be shortened using logical masking to the following code:

```
A = [1 3 5; 7 9 11; 11 9 7];
B = A > 5;
A(B) = A(B) - 2;
```

Or even shorter:

```
A = [1 3 5; 7 9 11; 11 9 7];
A(A > 5) = A(A > 5) - 2;
```

This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0

This website is not affiliated with Stack Overflow