Search code examples
matlaboperator-overloadinglogical-operatorslow-levelshort-circuiting

How to invoke short-circuit logical operators in MATLAB as a function?


MATLAB operators usually translate into a function form as in the following examples:

  • ~A => not(A)
  • A + B => plus(A,B)
  • A(...) => subsref(...)
  • A(...) = ... => subsasgn(...)
  • etc.

Now please consider the operators && and ||.

The various documentation (1-doc for or, 2-doc for and, 3-the MATLAB Programming Fundamentals ebook), does not shed any light on this, and nor do help and, help or, help relop. This also didn't help: profile('on','-detail','builtin').

What I can say is that | seems to be redirected to or() judging by the following example:

>> 1 || [0,0]    
ans =    
     1

>> 1 | [0,0]    
ans =    
     1     1

>> or(1,[0,0])    
ans =    
     1     1

>> 1 && [0,0]
Operands to the || and && operators must be convertible to logical scalar values.

So my question is: assuming it's possible - how can one explicitly call the underlying function of && and ||?

(note: this question deals with the aspect of "how", not "why")


Solution

  • There can't be a function implementing the underlying functionality. Assume there is a function scor which implements this operator, then calling scor(true,B) would evaluate B before calling scor, but the operator does not evaluate B.

    Obviously scor could be defined scor=@(x,y)(x||y), but it will evaluate B in the upper case.

    /Regarding the comment using function handles, this might be a workaround:

    %not printing a:
    true||fprintf('a')
    %printing a:
    scor=@(x,y)(x||y)
    scor(true,fprintf('a'))
    %not printing a:
    scor(true,@()(fprintf('a')))