MATLAB Lesson 3 - Vectors

Column vectors

In MATLAB you can also create a column vector using square brackets [ ]. However, elements of a column vector are separated either by a semicolon ; or a newline (what you get when you press the Enter key).

Create a column vector x with elements x1 = 1, x2 = -2 and x3 = 5.

Square brackets are used to create both row and column vectors.

The elements may be separated either by semicolons or newlines.

>>  x = [1; -2; 5]
>>  x = [1
-2
5]

 

The elements of a vector may be the result of arithmetic operations.

Create a column vector y with elements giving
  • 30 inches in cm (1 inch = 2.54cm),
  • 120 degrees Fahrenheit in Centigrade (C = 5(F - 32)/9),
  • 180 lbs in kilograms (one kilogram = 2.2 lbs).

    Square brackets are used to create a column vector, whose elements are MATLAB expressions, separated by semicolons.

    >>  y = [30/2.54; (5/9)*(120 - 32); 180/2.2]

     

    Operations with row/column vectors

    Elements of a column vector are accessed using round brackets ( ), exactly the same as for row vectors.

    Add row and column vectors

    Try the following commands in MATLAB:
    ans =
       4 5 6
       5 6 7
       6 7 8
    The result is a 3-by-3 matrix, with each element (i,j) in the matrix is equal to x(i) + y(j).
    >>  x = [1 2 3]
    >>  y = [3; 4; 5]
    >>  z = x + y

     

    The size command

    This will be even more important when we work with matrices in Lesson 5.

     

    Transpose

    You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe).

    Try the following MATLAB commands:

    [1 3 5] is a row vector, but the ' converts it into a column vector before the result is stored in the variable x.

    [1; 3; 5] is a column vector, but the ' converts it into a row vector before the result is stored in the variable y.

    >>  x = [1 3 5]'

    >>  y = [1; 3; 5]'


     

    Warnings

     

    Self-test Exercise

    Which of the following MATLAB expressions are valid and is the result a row vector or a column vector?

    • u1 = [1:3]
    • u2 = [1:3]'
    • u3 = 3*u1
    • u4 = u1 - u2
    • u5 = 4*u1 + u2'

    Answer: u1, u3 and u5 are valid row vectors, while u2 is a valid column vector. To understand u4 please type help + to get more information on how Matlab (after 2016) adding row and column vectors.
    Use the mouse to select the text between the word "Answer" and here to see the answer.

    Summary

    Column vectors are created using square brackets [ ], with semicolons or newlines to separate elements.

    A row vector may be converted into a column vector (and vice versa) using the transpose operator '.