Is there any way to simplify the following two line process into a single line?
e = eye(n);
e = e(:,k);
Note: This gets the k-th n-dimensional standard basis vector.
Is there any way to simplify the following two line process into a single line?
e = eye(n);
e = e(:,k);
Note: This gets the k-th n-dimensional standard basis vector.
As Matlab automatically pads zeros, you can use:
e([n,k])=[0,1]
Note that this line may produce wrong results when e already exists. To deal with the case k=n
, e(n)=0
comes first, then is overwritten by e(k)=1
I don't know about one line but this is a more (at least memory) efficient method:
e = zeros(n,1);
e(k) = 1;
Also if you're after elegance and readability then consider just encapsulating this into a function:
function e = basis_vector(n,k)
e = zeros(n,1);
e(k) = 1;
end