Changing [2,4] into [0,1,0,0,0,1] in Matlab

Good day, I apologize for the very vague title, I didn't really know how to formulate what I want. However, I can explain what I mean:

I have a vector v1:

v1 = [n1, n2, n3, .... ni]


And I want to create a new vector from this

g1 = [n1-1 zero's, 1, n2-1 zeros, 1, ... ni-1 zeros, 1]


Now, I don't really know where to begin with this. I suppose for the zero's I can just use the command zeros(1,ni-1), but then I don't even know where to begin in imlementing this in Matlab in order to create g1.

I do of course know that the length of g1 will be equal to sum(v1). I suppose maybe it'll have to be some sort of double for loop?

I understand that I'm not giving you much, but I hope that maybe someone could give me a push in the right direction?

% Try the following
% Tested on GNU Octave, but should work on Matlab

v1 = [2,4] ;
g1 = [] ;

for k=1:1:length(v1)
g1 = [g1 zeros(1,v1(1,k)-1) 1] ;
end ;

• This also works, and is even shorter! :) Thanks Feb 17 '14 at 11:55
• No problem. Either solution works - choose whichever one you feel like using. Feb 17 '14 at 12:05

You can do it in the following way :

g1 = zeros([1 sum(v1)]) ;   % this is as you said

for i = 1:size(v1,2)
temp = v1(1:i)    ;
g1(sum(temp)) = 1 ;         % only index those numbers which you want to set 1
end

• Man, it's amazing how simple things can be sometimes. Very efficient. Thank you very much! Feb 17 '14 at 11:44
• wait there is a little mistake let me update it ! Feb 17 '14 at 11:45
• now its working ! Feb 17 '14 at 11:49
• Haha, indeed. It seemed correct, and then I tested it and realized that it wasn't putting the sequences after each other, but instead putting the 1's at the values of v1(i). But you took care of that :) Feb 17 '14 at 11:51
• (fyi I've rolled back your change to the title of the question: backquotes don't seem to work in titles) Feb 17 '14 at 12:19

In Matlab it's better to avoid loops. That way code runs faster and it's easier to write and read. In this case you can achieve your desired result in one line using cumsum:

g1(cumsum(v1)) = 1;


Note that Matlab automatically fills with zeros. That's why I don't need to initialize g1.

• Having said you don't need to initialise, it can be more efficient to allocate the memory first and then index using array notation. Feb 22 '14 at 23:46