Reputation: 11686
For example, given i=5
and and n=8
, I want to generate [0;0;0;0;1;0;0;0]
. Specifically, I want to generate the vector v
so that:
v = zeros(n,1);
v(i) = 1;
Is there a (reasonable) way to do this in one line?
Upvotes: 9
Views: 8895
Reputation: 42225
Here's another solution using sparse
to create an n
length row vector with a 1 in the i
th position:
v = sparse(1,i,1,1,n)
The advantage is that for large n
, this is also memory efficient and can be used as usual in matrix calculations. If you ever need the full vector, just use full
.
Upvotes: 5
Reputation: 19793
Another solution:
I = eye(n);
v = I(:, i);
Actually, you can have a vector y
of numbers from 1 to n and get vectors like this for each element:
v = I(:, y);
You can see my blog post for the details on this general solution.
Upvotes: 14
Reputation: 20915
Here is another one:
n = 8;
p = 4;
arrayfun(@str2double,dec2bin(2^(p-1),n))
And another one (Creates a row vector):
circshift( [1 zeros(1,n-1)],[0 p]);
Or a column vector:
circshift( [1 ; zeros(n-1,1)],[p 0]);
Here is another one:
subsref( eye(n), struct('type','()', 'subs',{{ p,':' }}))
Upvotes: 1