Snowball
Snowball

Reputation: 11686

Matlab/Octave one-liner for a n-vector with a 1 in the i-th position

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

Answers (4)

abcd
abcd

Reputation: 42225

Here's another solution using sparse to create an n length row vector with a 1 in the ith 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

topchef
topchef

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

Andrey Rubshtein
Andrey Rubshtein

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

Snowball
Snowball

Reputation: 11686

One way is [1:8]'==5, or more generally [1:n]'==i

Upvotes: 13

Related Questions