Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 816
Finn Avatar asked Apr 10 '19 12:04

Finn


People also ask

How to reference a part of a matrix in MATLAB?

The most common way is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A .

Do MATLAB arrays start at 1?

In most programming languages, the first element of an array is element 0. In MATLAB, indexes start at 1. Arrays can be sliced by using another array as an index.

Is MATLAB zero indexed?

MATLAB does not allow an index of zero into an array unless you are performing logical indexing using a vector including a logical 0 and want to ignore the corresponding element of the array into which you are indexing.


2 Answers

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.

like image 91
Wolfie Avatar answered Oct 19 '22 04:10

Wolfie


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
like image 24
Adriaan Avatar answered Oct 19 '22 04:10

Adriaan