简体   繁体   中英

MatLab: Creating a Vector

Can I create a vector v3 = [1,100,2,99,3,98,...,100,1] using just colon notation?

I've only managed to create it using a loop.

Try this. No MATLAB on this machine so apologies if it doesn't work entirely.

vforward = [1:100];
vback = [100:-1:1];
vtot = [vforward; vback];
vtot = vtot(:)

An alternative version that doesn't require reshaping:

v3 = zeros(1,200);
v3(1:2:end) = 1:100;
v3(2:2:end) = 100:-1:1; %# or: fliplr(v3(1:2:end))

This is the best that I could manage on a Sunday morning:

cumsum([1, ((-1).^(mod(0:198,2))).*(99:-1:-99)])

It's only merit wrt to the other answers is that it is a one-liner. Which may not be much of a merit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM