The zeros Function

The zeros function produces an array or matrix filled with zeros, but of a defined size:

The zeros Function

The zeros function allows you, the programmer, to create an "empty array"... okay its not really empty, it has a bunch of zeros in it. There are two reasons to do this.

  1. You are creating a list of counters, and counting starts at 0.
  2. You are creating a very large array and need to "pre-allocate" the memory (i.e., reserve enough space so the computer doesn't have to get more buckets later).

The zeros function is very easy to use. It takes one or two values. If one value (lets call it N), then it creates an N by N matrix of 0s. If two values (lets call them rows, cols) it creates a rows by cols matrix. If rows or cols is 1, then we get an array.

        
          % create an array with 1 row, X columns where, x is the number of students in the class
          initial_grades = zeros(1, students_in_class);

          initial_grades =

                 0 0 0 0 0 0 0 0 ... 0


          % create a matrix with 5 rows and 5 columns, all with 0s
          zero_matrix = zeros(5);

          zero_matrix =
          
               0     0     0     0     0
               0     0     0     0     0
               0     0     0     0     0
               0     0     0     0     0
               0     0     0     0     0
        

      

Back to Topics List