Edit: I thought of a different (slightly obscure), but shorter way to do this, and it is faster than the loop.
for rep=1:100000 #% original loop-based solution end toc Elapsed time is 2.768822 seconds. #% bsxfun-based indexing alternative tic; for rep=1:100000 TempVec=abs(Vec);TempVec(Vec==0)=1; LongVec = sign(Vec(sum(bsxfun(@gt,1:sum(TempVec),cumsum(TempVec)))+1)) end toc Elapsed time is 1.798339 seconds.
This answer is also very well evaluated compared to the original - at least to a certain extent. There is a good place.
Vec = repmat(OrigVec,10,1);
bsxfun decomposes the vector into a matrix, and then collapses it with the sum. With very large vectors, this is unnecessarily heavy in memory compared to a loop, so it ends up losing. Until then, however, all is well.
Original, slow answer:
Here is a single line:
out=cell2mat(arrayfun(@(x) repmat(((x>0)*2)-1+(x==0),max(1,abs(x)),1),Vec,'uni',0)); out' = 0 1 1 1 -1 -1 -1 -1 0 0 1 1 1 -1
What's happening:
((x>0)*2)-1 + (x==0)
source share