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 ?

 Respuesta aceptada

Voss
Voss el 26 de Oct. de 2022

1 voto

4 comentarios

Quang Nguyen
Quang Nguyen el 26 de Oct. de 2022
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 el 26 de Oct. de 2022
Editada: Voss el 26 de Oct. de 2022
% 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 el 26 de Oct. de 2022
Thank you very much, i really get it now
Voss
Voss el 26 de Oct. de 2022
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 26 de Oct. de 2022

Comentada:

el 26 de Oct. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by