Cam
Cam

Reputation: 15234

What's the most idiomatic way to create a vector with a 1 at index i?

In Matlab, suppose I would like to create a 0-vector of length L, except with a 1 at index i?

For example, something like:

>> mostlyzeros(6, 3)

ans =

     0     0     1     0     0     0

The purpose is so I can use it as a 'selection' vector which I'll multiply element-wise with another vector.

Upvotes: 3

Views: 415

Answers (6)

Yanai Ankri
Yanai Ankri

Reputation: 439

Another one line option, which should be fast is:

vec = sparse(1, ii, 1, 1, L);

Upvotes: 1

H.Muster
H.Muster

Reputation: 9317

Just for the fun of it, another one-liner:

function [out] = mostlyzeros(idx, L)
out([L, idx]) = [0 1];

Upvotes: 2

Colin T Bowers
Colin T Bowers

Reputation: 18560

I'm having a hard time thinking of anything more sensible than:

Vec = zeros(1, L);
Vec(i) = 1;

But I'd be happy to be proven wrong!

UPDATE: The one-liner solution provided by @GlenO is very neat! However, be aware that if efficiency is the chief criteria, then a few speed tests on my machine indicate that the simple method proposed in this answer and the other two answers is 3 or 4 times faster...

NEXT UPDATE: Ah! So that's what you mean by "selection vectors". @GlenO has given a good explanation of why for this operation a vector of ones and zeros is not idiomatic Matlab - however you choose to build it.

ps Try to avoid using i as a subscript, since it is actually a matlab function.

Upvotes: 2

Glen O
Glen O

Reputation: 733

The simplest way I can think of is this:

a = (1:N)==m;

where N>=m. Having said that, if you want to use the resulting vector as a "selection vector", I don't know why you'd multiply two vectors elementwise, as I would expect that to be relatively slow and inefficient. If you want to get a vector containing only the m-th value of vector v in the m-th position, this would be a more straightforward method:

b = ((1:N)==m)*v(m);

Although the most natural method would have to be this:

b(N)=0;
b(m)=v(m);

assuming that b isn't defined before this (if b is defined, you need to use zeros rather than just assigning the Nth value as zero - it has been my experience that creating a zero vector or matrix that didn't exist before that is most easily done by assigning the last element of it to be zero - it's also useful for extending a matrix or vector).

Upvotes: 11

Teod0r
Teod0r

Reputation: 13

I would simply create a zero-vector and change whatever value you like to one:

function zeroWithOne(int numOfZeros, int pos)
a = zeros(numOfZeros,1);
a(pos) = 1;

Upvotes: 1

Autonomous
Autonomous

Reputation: 9075

I can think of:

function mostlyones(m,n)

mat=zeros(1,m);
mat(n)=1;

Also, one thing to note. In MATLAB, index starts from one and not from zero. So your function call should have been mostlyzeros(6,3)

Upvotes: 1

Related Questions