Morpheus
Morpheus

Reputation: 3543

create a positive vector with desired one norm

I want to generate a vector in Matlab and the vector should be non negative and the one norm should be equal to something which i can input(say 1).

I tried searching online but couldn't come up with satisfactory suggestions.

Upvotes: 0

Views: 715

Answers (2)

Suever
Suever

Reputation: 65460

You could just generate a random vector using rand and then use norm to compute the norm of the vector by which you would divide all elements. You could then multiply the result by your input value to scale it to the desired length.

If you want the L1 norm, you would use the following.

% This will use the L1 norm
vec = rand(1, 10);
vec = vec * scale ./ norm(vec, 1);

This could be generalized to the p norm with the following:

vec = rand(1, 10);
vec = vec * scale ./ norm(vec, p);

Upvotes: 4

Dan
Dan

Reputation: 45752

Generate elements between 0 and 1 (i.e. non-negative by definition) randomly:

v = rand(n,1)

Then scale it by diving by it's one norm (i.e. it now has a one norm of 1) and multiplying by your desired one norm, k:

V = k*v/norm(v,1)

Upvotes: 2

Related Questions