Joel
Joel

Reputation: 30156

Initialise a vector with 1's at indexes set in another vector

Given a vector:

v1 = [1 ; 3; 5]

and without using a for loop how could you create a new vector v2 of length n with:

each element of v2 set to 1 if it's index is in v1, 0 otherwise.

So for example, given the above v1 and n = 8 I would expect v2 to have values:

v2 = [1; 0; 1; 0; 1; 0; 0; 0]

Upvotes: 3

Views: 134

Answers (1)

mtrw
mtrw

Reputation: 35088

>> v2 = zeros(n,1);
>> v2(v1) = 1;

Upvotes: 7

Related Questions