What's the most idiomatic way to create a vector with a 1 at index i?
matlab, vector
Solution
The simplest way I can think of is this:
a = (1:N)==m;
where N>=m. Having said that, if you want to use the resulting vector as a "selection vector", I don't know why you'd multiply two vectors elementwise, as I would expect that to be relatively slow and inefficient. If you want to get a vector containing only the m-th value of vector v in the m-th position, this would be a more straightforward method:
b = ((1:N)==m)*v(m);
Although the most natural method would have to be this:
b(N)=0;
b(m)=v(m);
assuming that b isn't defined before this (if b is defined, you need to use zeros rather than just assigning the Nth value as zero - it has been my experience that creating a zero vector or matrix that didn't exist before that is most easily done by assigning the last element of it to be zero - it's also useful for extending a matrix or vector).
Problem
In Matlab, suppose I would like to create a 0-vector of length `L`, except with a 1 at index `i`? For example, something like: ``` >> mostlyzeros(6, 3) ans = 0 0 1 0 0 0 ``` The purpose is so I can use it as a 'selection' vector which I'll multiply element-wise with another vector.