0
votes

I have a matrix A of size say 5x7.

If I want to get a logical matrix out of A based of the elements that satisfy certain conditions, I can do this:

A = [10    47    16    33    47    11    10
    19    39    26    19    44    16    12
    32    25    26    41    28    24     9
    40    22    41    27    32    12    12
     5    23    40    18    30    43    22]

>> A > 25 | A < 10

ans =

 0     1     0     1     1     0     0
 0     1     1     0     1     0     0
 1     0     1     1     1     0     1
 1     0     1     1     1     0     0
 1     0     1     0     1     1     0

Problem: If I want to specify conditions for the row and column indices, what is the best way to do it?

I have a condition like i (row sub) should be less than j (column sub).

I could do this using triu but is there any simple way using logical indexing?

Expected output

0    1    1    1    1    1    1
0    0    1    1    1    1    1
0    0    0    1    1    1    1
0    0    0    0    1    1    1
0    0    0    0    0    1    1

Another example:

Size: 5x3

Condition: (i > j+1) | i == 1 | i == 2

Expected Output:

 1     1     1
 1     1     1
 1     0     0
 1     1     0
 1     1     1
2

2 Answers

1
votes

You have two types of conditions here, conditions on the location of elements, and conditions on the value of elements. What I'd do is create 2 matrices, one for the locations, and one for the values:

loc = triu(ones(size(A)),1)
val = A > 25 | A < 10

and then combine them using or:

or(loc,val) %// or loc|val

If you wanted to use logical indexing (i.e. not triu/tril/etc.), then I think you'd have to create matrices of indices and do logical indexing on them:

[I,J]=ndgrid(1:size(A,1),1:size(A,2))
loc=I>J+1
3
votes

I figured an approach using bsxfun

[rows, cols] = size(A);

out = bsxfun(@(A,B) A > B+1 | A == 2 | A == 1 ,(1:rows).',1:cols);

Results:

>> out

out =

 1     1     1     1     1     1     1
 1     1     1     1     1     1     1
 1     0     0     0     0     0     0
 1     1     0     0     0     0     0
 1     1     1     0     0     0     0