MATLAB Answers

Raldi
0

Quickly create a vector of ones and zeros

Asked by Raldi
on 5 May 2014
Latest activity Commented on by Innocent Okoloko on 27 Feb 2019
My question is if there is a way to create a vector of zeros
vec =
0 0 0 0 0 0 0 0
and specify a position lets say from the second until the fourth element to be ones.
vec =
0 1 1 1 0 0 0 0
Is there a quick way of doing this in Matlab avoiding loops?

  0 Comments

Sign in to comment.

4 Answers

Answer by Youssef Khmou
on 5 May 2014
 Accepted Answer

vectorization is possible :
N=10;
vec=zeros(N,1);
positions=[2:4];
vec(positions)=1;

  4 Comments

Show 1 older comment
For this short code the bracket is not superfluous. x=zeros(1,21) gives you a 1 by 21 matrix, which you may need to carefully index if you want to use x in oher calculations. Here the square brackets just give you a single vector x. You can indeed see that its about the shortest code for the task.
positions = 2:4;
would do, so the square brackets ARE superfluous ...
You are right. Indeed x=zeros(1,21) will give the same result, makingthe code even shorter and more efficient. I had previously encountered a situation that made me adopt the sqaure brackets and I tried to ransack through my codes, not enough time to do all that now. I guess it is just useful for contantenation e.g.
num=ones(1,5);
num=[num zeros(1,10)]

Sign in to comment.


Answer by Matt J
on 5 May 2014
Edited by Matt J
on 5 May 2014

N=10;
positions=[2:4];
vec=sparse(1,positions,1,1,N);
and then optionally, if you want the vector in full form,
vec=full(vec),

  0 Comments

Sign in to comment.


Answer by Innocent Okoloko on 26 Feb 2019

Faster coding
x=[zeros(1,10)];
x(2:4)=1

  2 Comments

Note that the square brackets are superfluous, and likely slow down the code:
x = zeros(1,10)
will give the same result as your code, so the square brackets ARE superfluous ...

Sign in to comment.


Answer by Jos (10584)
on 26 Feb 2019

N = 10 % final length of NewVec
pos1 = 3 % start index of the 1's
n1 = 4 % number of 1's
% one-liner. NewVec should not exist yet
NewVec([N pos1:pos1+n1-1]) = [0 ones(1,n1)]

  0 Comments

Sign in to comment.