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 ?

 Accepted Answer

Voss
Voss on 26 Oct 2022

4 Comments

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
You're welcome!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 26 Oct 2022

Commented:

on 26 Oct 2022

Community Treasure Hunt

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

Start Hunting!