0

I have an n x n matrix in MATLAB. I am trying to iterate through each row and column of this matrix. If the value in each element is higher than a certain threshold, I want to replace that element with a 1. If the value in each element is lower than a certain threshold, I want to replace that element with a 0.

I am trying to use two for loops, but it's not leading me anywhere.Any suggestions?

A. L
  • 19
  • 2

1 Answers1

1

I suggest logical indexing.

A = randi([1 20],6,6);
Threshhold = 13;
A(A<Threshhold) = 0;
A(A>=Threshhold) = 1;

Before:

>> A = randi([1 20],6,6)
A =
     7     1    20     3     2    15
    16    13    11     3    11     7
     5     2     1     5    10    16
     5    14     8    14    11     8
    16    11     7    20    20    17
    10     1     2    10     6    12

After:

>> A
A =
     1     0     0     0     1     0
     0     0     1     0     0     0
     0     0     0     1     0     0
     1     1     1     0     1     1
     0     0     0     1     0     0
     0     0     0     0     0     0

Hope that helps.

Update:
Per @Cris Luengo from comments, Other approaches include A=double(A>=Threshold) or equivalently A=+(A>=Threshold).

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41