Home > database >  MATLAB overloading `end` not working as expected
MATLAB overloading `end` not working as expected

Time:08-30

classdef Array
    properties
        data = [1 2 3];
    end

    methods
        function ind = end(obj, k, n)
            ind = length(obj.data) - k;
        end
    end
end

A=Array(), if we do A(end) and breakpoint into out = length..., we'll see k=1, yet docs say

A(end-1)

is same as A(ind), where

ind = end(A,1,1)

so A(end) should be same as end(A,0,1)? In fact k=1 also with end-1, end-9 and any other.

For my purpose where I override subsref I simply set ind = length(obj.data) and it works, so it appears as if end is treated as constant and e.g. end - 1 is processed later, but this seems against docs.

CodePudding user response:

I agree that the documentation for this function is not very clear.

ind = end(A,k,n)
The arguments are described as follows:

A is the object
k is the index in the expression using the end syntax
n is the total number of indices in the expression
ind is the index value to use in the expression

What they mean to say is that end appears in the kth index out of n. So in an indexing expression like A(end-9), k and n are both 1 because end appears in the first dimension out of 1 dimensions. With A(end-1, end 1), end is called twice, once with k=1, n=2, and once with k=2, n=2. You can make the indexing operation work differently depending on how many dimensions are indexed. The most obvious use in MATLAB is the distinction between linear indexing and multi-dimensional indexing, where if n=1, end returns numel(A), no matter how many dimensions A actually has.

No matter how complex the computation that uses end, it should always return the number of elements (or rather, the index to the last element) along the given dimension. MATLAB will then use the returned value in the computation. This actually allows very complex operations involving end within an indexing expression, for example A(min(5,end)).


One of my grievances with the end operator is that there is no distinction between the type of indexing, () or {}. So you cannot have these two indexing operators do different things if you want to enable the use of end.

  • Related