Is there a way to change the size (and direction) of the step of the a:s:b function?

28 Views Asked by At

What is the shortest way to get

x =

     2    -2     4    -4     6    -6     ...     14    -14    16   -16

I figured out two options, one of them somewhat short:

>>x=[];  
for k=2:2:16  
x=[x k -k];  
end  
x

However, I wonder if it's possible to affect size and direction of the s in a:s:b, since the sequence above can be constructed with a regular pattern: +2, -4, +6, -8, +10 etc. That would be even shorter.

2

There are 2 best solutions below

1
On BEST ANSWER

A two-line solution without a loop:

xt = [2:2:16; -(2:2:16)]; x = xt(:)'

xt is 2 by 8. Since the (:) operation outputs it as a single column vector by concatenating each successive column of xt, the desired result is obtained by transposing.

0
On

Reshaping matrices may be another solution.

reshape([2:2:16; -(2:2:16)],1,16)