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

4 个评论

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 ?
% 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.
Thank you very much, i really get it now

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by