Working with arrays

Review questions

  • What is an array?
  • If A is an array, what is A(3,4)?
  • If A is an array, how to access its third row?

Arrays

We already studied the concept of arrays/matrices.

  • Arrays are the fundamental representation of data.
  • Arrays can contain numerical data and data of other types, but we cannot mix data types in a single array directly.
  • Arrays can organize multidimensional data.
  • The size of an array can be changed dynamically.
  • Indices for arrays are "1-based".

Creating arrays

A 1-dimensional array can be created by listing the entries within a pair of square brackets:


        a = [1 2 3 4]
    

A 2-dimensional array can be created in a similar way with semi-colon used as row separator (line break is fine too).


        a = [1 2 3; 4 5 6; 7 8 9]
    

Other ways

  • Range: a = 3:9
  • Range with steps: a = 3:0.5:9
  • Zeros: a = zeros(3,4)
  • Ones: a = ones(3,4)
  • Random numbers: a = rand(3,4)
  • Logical 1s: a = true(3,4)
  • Logical 0s: a = false(3,4)

Creating grids

Equally space points are often useful in applications.

  • a = linspace(0,10,30)
  • a = logspace(0,3,30)
  • [X,Y] = meshgrid(x,y)

Determining size/shape

  • Length (largest dimension) length(A)
  • Array size size(A)
  • Number of dimensions ndims(A)

Array indexing

  • A(3,:)
  • A(:,3)
  • A(1:3,2)