3

I have seen some code that uses:

index = findstr('something', 'longer string');
if ~isempty(index)
  % do something
end

I looked up the documentation for MatLab symbols here and it doesn't mention anything about using ~ for converting primitive integer values into boolean. i.e. if index is 10 or if it is [] then isempty will return 0 or 1 which will be converted to 1 or 0 with the ~ operator. However this use case isn't mentioned in the docs. Is this a legitimate way of performing negation. Is there another way of achieving this negation?

Quatermain
  • 145
  • 4
  • 1
    [`Is A==0 really better than ~A?`](http://stackoverflow.com/questions/25339215/is-a-0-really-better-than-a) might be relevant. – Divakar Oct 22 '15 at 18:22

2 Answers2

2

In the workspace, enter

doc not

or

doc ~

You will have an answer from the documentation of Matlab.

the_candyman
  • 1,563
  • 4
  • 22
  • 36
1

This use case is mentioned in the docs exactly where your link points to (see "Not Equal To" and "Logical NOT" under "Tilde -- ~"). You can also enter help ~ in the MATLAB console and get an explanation about usage.

This is the legitimate way of performing negation of a boolean. You can apply it to 0 and 1 to flip them, but it will also treat any non-zero value as a 1.

Another way to perform negation of x would be x = 1 - x, but that only works if x is boolean. So for the code you posted, you could do this:

index = findstr('something', 'longer string');
if 1 - isempty(index)
  % do something
end
Brian Lynch
  • 542
  • 5
  • 13
  • Note that you can also convert to boolean with `logical(10)`, so you could use `1-logical(x)`. But that's basically `~x` anyway. – Andras Deak -- Слава Україні Oct 22 '15 at 18:28
  • I think the original question is sound. It's not obvious from "To test for inequality values of elements in arrays a and b for inequality, use a~=b" if the tilde is valid to be used with a primitive integer value and what it would produce. The "Logical not" part of the documentation linked to similar just talks about arrays: "To find those elements of an array that are zero, use: ~a". It would be rash to make an assumptions about the return value from an operator on an integer when the only mentioned is of working with arrays. – AJP Oct 23 '15 at 20:57
  • Certainly, and of course most other languages use ! instead of ~. Hope my answer doesn't come across as suggesting it is a bad question. – Brian Lynch Oct 23 '15 at 21:13