Skip to main content
Logo image

Section 2.8 Array Functions

There are many built-in functions for dealing with arrays. Here are a few of them:
  • length(v) returns the number of elements in a vector (number of columns for a matrix)
  • size(a) returns a row vector that lists all of the dimensions of a. For example, if a is a \(m\times n\) matrix then size(a) = [m n].
  • reshape(a,m,n) rearranges the elements of a into a matrix with m rows and n columns. It is important to understand that the new shape is filled up with the elements of a column by column. If a itself is a matrix then its elements are read column by column to do so.
  • If v is a vector then diag(v) creates a matrix with the elements of v along the diagonal, zeros everywhere else. Such a matrix is called a diagonal matrix (since it only has non-trivial elements along its diagonal).
  • If a is a matrix then diag(a) creates a vector of the diagonal elements of a
Example using the reshape() function:
>> v = [3 4 5 6 7 8]
v =
    3 4 5 6 7 8
>> new = reshape(v, 2, 3)
new =
    3 5 7
    4 6 8
>> new2 = reshape(new, 1, 6)
new2 =
    3 4 5 6 7 8
Use the MATLAB Help function to find more useful functions: