Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

What a Difference It Makes!

I've been exploring some older functions in MATLAB recently and trying to characterize them. The function diff is one of them. And I realized it has a really unusual behavior when the optional dim input argument is omitted.


From the Documentation

Look in the documentation for diff under the section entitled "Tips". You will see this.

Since each iteration of diff reduces the length of X along dimension dim, it is possible to specify an order n sufficiently high to reduce dim to a singleton (size(X,dim) = 1) dimension. When this happens, diff continues calculating along the next nonsingleton dimension.


What! Try these statements.

ans =
     1     1     2
ans =
ans =

I know this behavior was not in the initial implementation of diff since I wrote it and would never be that cruel. But it did get added later. I can't see how it is useful at all. I will always use a specific dim input myself to ensure robustness of my code. But perhaps that's a failure of my imagination.

Is This Behavior Useful?

If anyone can come forth with a useful application of this aspect of the function diff, and prove it to me with working code in an application, I will spot the first such respondent with some MATLAB bling. Let me know here.

Published with MATLAB® 7.12

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.