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?
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].
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.
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 '.
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.
One way is [1:8]'==5
, or more generally [1:n]'==i
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With