Search code examples
arraysmatlabindexingmatrix-indexing

Create indexing array with 'end' before vector exists


I was just wondering if there is a way to index using end before knowing a vector's size? It should work for arrays with different sizes. Like this:

subvector = (2:end) % illegal use of end

A=[1 2 3];
B=[4 5 6 7];

A(subvector) % should be 2 3
B(subvector) % should be 5 6 7

Solution

  • You can set up an anonymous function to act in a similar way

    f_end = @(v) v(2:end);
    
    A = [1 2 3];
    B = [4 5 6 7];
    
    f_end( A ); % = [2 3];
    f_end( B ); % = [5 6 7];
    

    I think this is the only way you could do it, since you can't set up an indexing array without knowing the end index.