Matlab Array - Creating

Creating

  • The methods below create new arrays directly; they do not include constructing a new array by combining, concatenating, or slicing an existing one.

Direct Construction

Use square brackets [] together with commas , (or spaces) and semicolons ;:

  • List all elements inside []
  • Within a row, separate elements with , or whitespace
  • Separate rows with ;

Row Vectors

  • Arithmetic sequences
    • Operator :: <[start:<step>:end]>
      • All three operands are double
      • step defaults to 1
      • end need not be ≥ start; in that case step must be negative, otherwise the result is empty
      • The first element of the result is start; the last is start + floor((end - start) / step) * step
    • Function linspace
  • Geometric sequences

Column Vectors

  • Transpose operator '

2-D Arrays

A = [1 2 3; 2 5 6; 1 4 5];
B = [1:5; linspace(3, 10, 5); 3 5 2 6 4];
C = [[1:3]' linspace(2, 3, 3)' [3 5 6]'];

Special Arrays

  • Zero array: function Matlab Functions - zeros
  • Ones array: functionones
    • Same syntax as zeros, with 0 replaced by 1
  • Identity array: functioneye
    • Same syntax as zeros; 1 on the main diagonal, 0 elsewhere
    • Cannot create N-D (more than 2-D) arrays
  • Uniformly distributed random array: functionrand
    • Same syntax as zeros, with 0 replaced by samples drawn uniformly on
    • However,typename may only besingle ordouble
  • Normally distributed random array: functionrandn
    • Same asrand, with the uniform distribution on replaced by the standard normal distribution on
  • Logical array: functionstrue andfalse
    • Same syntax as zeros, with 0 replaced by logical 1/0; produces a logical array
    • Therefore there is notypename parameter
  • Diagonal array: function diag
  • Magic square: function magic