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

92 Views Asked by At

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?

3

There are 3 best solutions below

7
On BEST ANSWER

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 
2
On
% 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 ;
1
On

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.