# How can I create a vector like this : X = [1, 2, 1, 2 ......

50 views (last 30 days)
cheng en tsai on 2 Mar 2021
Edited: Stephen Cobeldick on 2 Mar 2021
Hi,
How can I create a vector X = [ 1, 2, 1, 2 ....... ] with n value.(which n value can be odd or even).
Is there possible to use only two instructions?
thanks.
##### 2 CommentsShowHide 1 older comment
cheng en tsai on 2 Mar 2021
If I want it to use only one assignment statement, how can I deal with it especially when n is odd?

Stephen Cobeldick on 2 Mar 2021
n = 9;
v = 2-mod(1:n,2)
v = 1×9
1 2 1 2 1 2 1 2 1
Stephen Cobeldick on 2 Mar 2021
@Walter Roberson: yes, I also noticed that.
I suspect that "instructions" is as equally well-defined by the same professors/tutors/teachers who also specify no "inbuilt" functions. In some sense, even the hard-coded numbers are "instructions" to the MATLAB parser.
Perhaps the person who set this assignment can clarify this for us.

Matt J on 2 Mar 2021
Edited: Matt J on 2 Mar 2021
X=ones(1,n);
X(2:2:end)=2;
Walter Roberson on 2 Mar 2021
three instructions

R2020b

### Community Treasure Hunt

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

Start Hunting!