What are the semantics of ‘end’ in Matlab?

Firstly, I think it’s kind of a bug, or at least an unexpected feature, that your syntax x(1:min(5, end)) works at all. When I was at MathWorks, I remember someone pointing this out, and quite a few of the developers had to spend a while figuring out what was going on. I’m not sure if they ever really agreed whether it was a problem or not.

To explain the (intended) semantics of end: end is implemented as a function ind = end(obj, k, n). k is the index of the expression containing end, and n is the total number of indices in the expression.

So, for example, when you call a(1,end,1), k is 2, as the end is in argument 2, and n is 3 as there are 3 arguments.

ind is returned as the index that can replace end in the expression.

You can overload end for your own classes (in the same way as you can overload colon, size, subsref etc).

To extend your example:

classdef IndexDisplayer
  methods
    function ind = end(self,k,n)
        disp(k)
        disp(n)
        ind = builtin('end', self, k, n);
    end
  end
end

>> a = IndexDisplayer;
>> a(1,end,1)
 2
 3

See here for more information.

Leave a Comment