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 ;
  • $\begingroup$ This also works, and is even shorter! :) Thanks $\endgroup$ Feb 17 '14 at 11:55
  • 1
    $\begingroup$ No problem. Either solution works - choose whichever one you feel like using. $\endgroup$ 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
  • $\begingroup$ Man, it's amazing how simple things can be sometimes. Very efficient. Thank you very much! $\endgroup$ Feb 17 '14 at 11:44
  • $\begingroup$ wait there is a little mistake let me update it ! $\endgroup$
    – abkds
    Feb 17 '14 at 11:45
  • $\begingroup$ now its working ! $\endgroup$
    – abkds
    Feb 17 '14 at 11:49
  • $\begingroup$ 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 :) $\endgroup$ Feb 17 '14 at 11:51
  • $\begingroup$ (fyi I've rolled back your change to the title of the question: backquotes don't seem to work in titles) $\endgroup$
    – TooTone
    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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.