Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert digit to vector octave/matlab [duplicate]

I have a vector y = [0; 2; 4]

I want to convert each element of it into vector, where all elements are zero but element with index equal to digit is 1.

I'd like to do it without loops.

For example [0; 2; 4] should be converted to

[1 0 0 0 0 0 0 0 0 0;
 0 0 1 0 0 0 0 0 0 0;
 0 0 0 0 1 0 0 0 0 0]

(in this example vector first index is 0)

like image 841
Poni Poni Avatar asked Feb 07 '26 17:02

Poni Poni


1 Answers

The usual trick with sparse can be used to simplify the process. Let n denote the desired number of columns. Then

result = full(sparse(1:numel(y), y+1, 1, numel(y), n));

For example, y = [0;2;4] and 10 produce

result =
     1     0     0     0     0     0     0     0     0     0
     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     1     0     0     0     0     0
like image 106
Luis Mendo Avatar answered Feb 09 '26 10:02

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!