Concatenate array using square brackets

x = zeros(1,9);
x = [1, x(1:9)];
when i run the second line multiple times, it starts to fill in the array x. I want to ask what is the functionality of the second line, and is there any documentation that describes this syntax ?

 採用された回答

Voss
Voss 2022 年 10 月 26 日

1 投票

4 件のコメント

Quang Nguyen
Quang Nguyen 2022 年 10 月 26 日
this seems like concatenating another array at the end of the first array, instead of replacing the zeros with the value 1 like the code i showed. Or is there any thing i misunderstand ?
Voss
Voss 2022 年 10 月 26 日
編集済み: Voss 2022 年 10 月 26 日
% x is a 1-by-9 array (i.e., a vector) of 9 zeros:
x = zeros(1,9)
x = 1×9
0 0 0 0 0 0 0 0 0
% now x is a 1 followed by the first 9 elements of what was x (i.e., 9 zeros)
x = [1, x(1:9)]
x = 1×10
1 0 0 0 0 0 0 0 0 0
% now x is a 1 followed by the first 9 elements of what was x (i.e., a 1 and 8 zeros)
x = [1, x(1:9)]
x = 1×10
1 1 0 0 0 0 0 0 0 0
% now x is a 1 followed by the first 9 elements of what was x (i.e., two ones and 7 zeros)
x = [1, x(1:9)]
x = 1×10
1 1 1 0 0 0 0 0 0 0
% etc.
Perhaps it's useful to see the same code operating with a different starting vector x:
x = 1:9
x = 1×9
1 2 3 4 5 6 7 8 9
x = [1, x(1:9)]
x = 1×10
1 1 2 3 4 5 6 7 8 9
x = [1, x(1:9)]
x = 1×10
1 1 1 2 3 4 5 6 7 8
x = [1, x(1:9)]
x = 1×10
1 1 1 1 2 3 4 5 6 7
Considering that example, it may be more clear now, that the line x = [1, x(1:9)] does not really "replace" zeros with ones, but instead prepends a 1 to the beginning of x and removes anything after element #9, each time it is run.
Quang Nguyen
Quang Nguyen 2022 年 10 月 26 日
Thank you very much, i really get it now
Voss
Voss 2022 年 10 月 26 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2022 年 10 月 26 日

コメント済み:

2022 年 10 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by