How to create array with unequal spacing?

I want to create an array with unequal spacing. I have h = 1 1/2 1/4 1/8 ..... 2^-60.
Every second entry in this array is 1/2 of the last one. I only know, how to make arrays with equal spacing.
a = 1:5:40
But how do I create array that gets halved with every entry?

5 Comments

For the special case of binary powers it may be more efficient to use pow2:
h = pow2(0:-1:-60)
timeit() disagrees:
>> timeit(@() pow2(0:-1:-60),0)
ans =
3.45591429508197e-06
>> timeit(@() 2.^-(0:60),0)
Warning: The measured time for F may be inaccurate because it is running too fast. Try measuring something that takes longer.
> In timeit (line 158)
ans =
0
And if you
>> tic;for K = 1 : 1000; h = 2.^-(0:60); end; toc
Elapsed time is 0.000007 seconds.
-- not the first time, at least not from the command line, but after a few times repeating the same line, the JIT fully kicks in.
By way of contrast,
>> tic;for K = 1 : 1000; h = pow2(0:-1:-60); end; toc
Elapsed time is 0.004652 seconds.
was the best I could do.
@Walter Roberson: Interesting. So what is the usecase for pow2(n) then?
In 2.^-(0:60) the JIT is detecting that the expression is constant and optimizes it, at least in the case of re-use. If you use B = 2; B.^-(0:60) or if you use V = -(0:60); 2.^B then JIT optimization is not as good and pow2 can have better performance than those.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!