octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: differences matlab vs octave


From: John W. Eaton
Subject: Re: differences matlab vs octave
Date: Wed, 9 May 2007 14:06:27 -0400

On  9-May-2007, David Bateman wrote:

| Nicolas Pettiaux wrote:
| > Thank you very much David.
| >
| > Can we put this in the Octave wiki and in wikibook as "definitive"
| > places that could allow for rapid change ?
| >
| > Nicolas
| >
| That was one of the reasons I sent it. I'd suggest adding
| 
| <quote>
| * The & and | operators in Matlab short-circuit when included in an if
| statemant and not otherwise. Whereas in Octave only the && and ||
| short circuit. This is due to the absence of && and || in Matlab
| till recently. Note that this means that
| 
|   if (a | b)
|     ...
|   end
| 
| and
|  
|   t = a | b;
|   if t
|     ...
|   end
| 
| are different in Matlab. This is really a matlab bug, but there is too
| much code out there that relies on this behavior to change it. Prefer
| the || and && operators in if statements if possible.

You might note that the difference is significant if either of the
arguments are functions with side effects or if the first argument is
a scalar and the second argument is an empty matrix.  For example,
note the difference between

  t = 1 | [];          ## results in [], so...
  if (t) 1, end        ## in if ([]), this is false.

and

  if (1 | []) 1, end   ## short circuits so condition is true.

Another case that is documented in the Matlab manuals is that

  t = [1, 1] | [1, 2, 3];          ## error
  if ([1, 1] | [1, 2, 3]) 1, end   ## OK

Another thing to mention might be that Matlab requires the operands of
&& and || to be scalar values but Octave does not (it just applies the
rule that for an operand to be considered true, every element of the
object must be nonzero or logically true).

Finally, note the FUBARness of thinking of the condition of an if
statement as being equivalent to all(X(:)) when X is a matrix.  This
is true for all cases EXCEPT empty matrices:

  if ([0, 1]) == if (all ([0, 1]))   ==>  i.e., condition is false.
  if ([1, 1]) == if (all ([1, 1]))   ==>  i.e., condition is true.

BUT

  if ([]) != if (all ([]))

because all ([]) == 1 (because, despite the name, it is really
returning true if none of the elements of the matrix are zero, and
since there are no elements, well, none of them are zero).  But,
somewhere along the line, someone decided that if ([]) should be
false.  I guess it just looks wrong to have [] be true in this context
even if you can use logical gymnastics to convince yourself that "all"
the elements of a matrix that doesn't actually have any elements are
nonzero.

Happy Inconsistent Hacking,

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]