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?

1

2 Answers 2

2

In the workspace, enter

doc not

or

doc ~

You will have an answer from the documentation of Matlab.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Note that you can also convert to boolean with logical(10), so you could use 1-logical(x). But that's basically ~x anyway.
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.
Certainly, and of course most other languages use ! instead of ~. Hope my answer doesn't come across as suggesting it is a bad question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.