Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

matlab

octave

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?

like image 570
Snowball Avatar asked Jun 04 '12 03:06

Snowball


People also ask

How do you input a vector into octave?

Simply type [1 2 3] at the prompt, followed by enter, and observe the output on the screen). Vector elements can also be entered separated by commas. For example, the command octave#:#> B = [0.1,2,5] will create the row vector B=[0.1 2 5].

How do you write a vector in MATLAB?

You can create a vector both by enclosing the elements in square brackets like v=[1 2 3 4 5] or using commas, like v=[1,2,3,4,5]. They mean the very same: a vector (matrix) of 1 row and 5 columns. It is up to you.

Which option can be used to create a column vector?

Column vectors are created using square brackets [ ], with semicolons or newlines to separate elements. A row vector may be converted into a column vector (and vice versa) using the transpose operator '.

How do you create a row vector from a matrix in MATLAB?

Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.


2 Answers

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

like image 196
Snowball Avatar answered Sep 30 '22 07:09

Snowball


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.

like image 36
topchef Avatar answered Sep 30 '22 06:09

topchef