3

I'm getting an unexpected result from Matlab and I have no idea why. My goal is to replace values less than or equal to zero with Inf.

Here is the correct result of what I expect should happen:

C = [0 0 0 0 0 1 1 1 1 1 1];
C(C<=0)=Inf
C = Inf   Inf   Inf   Inf   Inf     1     1     1     1     1     1

But when I begin the process in a different manner, matlab replaces values <=0 with 1 instead of Inf.

A = [0     2     4     6     8    10    12    14    16    18    20];
b = 7;
E=A-b>0
E = 0     0     0     0     1     1     1     1     1     1     1
E(E<=0)=Inf
E = 1     1     1     1     1     1     1     1     1     1     1     

Any idea why this is occurring? I'm guessing it has something to do with logical E=A-b>0 step, but I don't know why it is different.

My overall goal is to find the index of the closest larger value of a vector to a scalar, and it did just occur to me that I could skip the step that I think is causing the problem and get the desired outcome, like so (with A & b already defined as above):

F=A-b
F = -7    -5    -3    -1     1     3     5     7     9    11    13
F(F<=0)=Inf
F = Inf   Inf   Inf   Inf     1     3     5     7     9    11    13
[~,ind]=min(F)
ind = 5

BUT, I still don't understand why Matlab was not giving the result I expected above (and I already finished typing the question before I realized the simple solution). So does anyone know why Matlab gives the unexpected result?

Thanks

agnuke
  • 55
  • 1
  • 2
  • 7

1 Answers1

4

This is because E is a logical array. Possible values are 1 or 0. If you use E=double(A-b>0) you will get the expected results.

Daniel
  • 36,610
  • 3
  • 36
  • 69