Section 2.6 Adding Elements to Arrays
Subsection 2.6.1 Adding to Vectors
Whereas in C, the size of an array was fixed throughout its existence, in MATLAB arrays can be dynamically resized without too much trouble. In fact, you can simple add on to an array by telling MATLAB new elements to be included. Let’s take a look at an example. Suppose we have a vector “ve”, for example as follows:
>> ve = 3:8
ve =
3 4 5 6 7 8
This vector has six elements: “ve(1)”, “ve(2)”, ..., “ve(6)”. We can add on to this vector by simply telling MATLAB about additional elements:
>> ve(7:9) = [2 2 2]
ve =
3 4 5 6 7 8 2 2 2
By specifying elements seven through nine MATLAB automatically resized the vector to make room for these new elements. In addition, MATLAB will kindly pad with zeros if you create a hole:
>> ve(12) = 1
ve =
3 4 5 6 7 8 9 2 2 2 0 0 1
Subsection 2.6.2 Adding to Matrices
Just as for vectors, matrices can easily have new elements appended to them as well as you can see from this example. Suppose we have a matrix defined as follows:
>> ma = [0 1 2 3; 4 5 6 7; 8 9 10 11; 12 13 14 15]
ma =
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
This matrix has four rows and four columns. If we specify a new row, for example row 6, then not only will MATLAB enlarge the matrix to hold 6 rows, but it will also pad the fifth row with zeros.
>> ma(6, :) = [16 17 18 19]
ma =
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
0 0 0 0
16 17 18 19
Finally, arrays can have more than two dimensions:
>> z = zeros(4, 2, 3)
z(:,:,1) =
0 0
0 0
0 0
0 0
z(:,:,2) = 0 0 0 0 0 0 0 0
z(:,:,3) = 0 0 0 0 0 0 0 0