Moderat
Moderat

Reputation: 1560

What is the `end+1` line doing here?

Consider the following bit of MATLAB code:

degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
    for j = 0:i
        out(:, end+1) = (X1.^(i-j)).*(X2.^j);
    end
end

I'm not sure I see how the end+1 index is functioning. There are no previously defined variables called end in this code.

Upvotes: 1

Views: 2462

Answers (2)

Eitan T
Eitan T

Reputation: 32930

Writing end as a subscript is equivalent to writing the index of last element in the array in the specified dimension, as stated in the official documentation:

The end function also serves as the last index in an indexing expression.
In that context, end = (size(x,k)) when used as part of the kth index. Examples of this use are X(3:end) and X(1,1:2:end-1).When using end to grow an array, as in X(end+1)=5, make sure X exists first.

In your case (highlighted in bold), out(:, end+1) means that the matrix out is growing in the second dimension with each iteration of i.

Upvotes: 4

aschepler
aschepler

Reputation: 72431

end is a keyword in Matlab which can be used an array index and always means the last element in that dimension.

So out(:, end) is the last column. out(end, :) is the last row. out(1, end) is the last element in the first row.

And here, when out(:, end+1) refers to a column past the end of the matrix, the assignment automatically grows the matrix, adding the just-computed vector as a new column on the right.

Upvotes: 2

Related Questions