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

2 ビュー (過去 30 日間)
cheng en tsai
cheng en tsai 2021 年 3 月 2 日
編集済み: Stephen23 2021 年 3 月 2 日
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 件のコメント
Walter Roberson
Walter Roberson 2021 年 3 月 2 日
Is there possible to use only two instructions?
No. You need a minimum of 3 instructions even for the case where n is even. You can construct 1:2 or [1 2] but either way that takes one instruction. You need to divide n by 2, which takes one instruction. Replicating the vector takes a minimum of 1 instruction.
You can do the whole thing in four instructions if it is acceptable to have two assignment statements. I think it might take 6 instructions if you are only permitted to use a single assignment statement.
cheng en tsai
cheng en tsai 2021 年 3 月 2 日
Thanks for replying.
If I want it to use only one assignment statement, how can I deal with it especially when n is odd?

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2021 年 3 月 2 日
n = 9;
v = 2-mod(1:n,2)
v = 1×9
1 2 1 2 1 2 1 2 1
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 3 月 2 日
Three instructions
Stephen23
Stephen23 2021 年 3 月 2 日
編集済み: Stephen23 2021 年 3 月 2 日
@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.

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2021 年 3 月 2 日
編集済み: Matt J 2021 年 3 月 2 日
X=ones(1,n);
X(2:2:end)=2;
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 3 月 2 日
three instructions

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by