6

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
Wolfie
  • 27,562
  • 7
  • 28
  • 55
Finn
  • 2,333
  • 1
  • 10
  • 21
  • I'm thinking the way you are trying to go about it would all result in illegal use of end. Maybe try making a string and see if you can convert the string to an index? Try [str2func](https://www.mathworks.com/help/matlab/ref/str2func.html) – medicine_man Apr 10 '19 at 13:15
  • [eval](https://www.mathworks.com/help/matlab/ref/eval.html) may work better for what you want. – medicine_man Apr 10 '19 at 13:23
  • 3
    @medicine_man Safely assume that `eval` never works *better* – Wolfie Apr 10 '19 at 13:33
  • 1
    @medicine_man read [this answer of mine](https://stackoverflow.com/a/32467170/5211833) and references contained therein to blogs by MathWorks employees amongst others as to why using `eval` is almost always a bad idea. – Adriaan Apr 10 '19 at 13:42
  • 1
    [The highest voted question in the MATLAB tag](https://stackoverflow.com/q/3627107/5211833) might be relevant here. Not a dupe, but closely related nonetheless. – Adriaan Apr 10 '19 at 13:44
  • Another closely related question: https://stackoverflow.com/questions/20508157/how-do-i-use-matlabs-substruct-function-to-create-a-struct-representing-a-refer – Cris Luengo Apr 10 '19 at 14:03
  • Haven't used eval much, but never any security problems or run time issues. – medicine_man Apr 10 '19 at 14:06
  • @medicine_man These articles might be of interest: [docs: "Alternatives to the eval function"](https://uk.mathworks.com/help/matlab/matlab_prog/string-evaluation.html), [MathWorks blog: "Evading eval"](https://blogs.mathworks.com/loren/2005/12/28/evading-eval/), SO questions: https://stackoverflow.com/q/46179940/3978545, https://stackoverflow.com/q/46213509/3978545 – Wolfie Apr 11 '19 at 09:25

2 Answers2

3

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.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
1

Without indexing or usage of end, one can remove the first element:

f_end = A;
f_end[1] = [];

As a function:

function x = f_end(y, n)
    x = y;
    x[1:n]=[]; % deletes the first n elements
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • I guess this involves an intermediate step, say if I wanted to use the indexed array but preserve the whole array, I'd have to create a copy and remove the initial elements? – Wolfie Apr 10 '19 at 13:37
  • @Wolfie yes, removing elements changes the shape of an array. This is indeed a drawback of the method. – Adriaan Apr 10 '19 at 13:39