MATLAB For Dummies, 2nd Edition
Book image
Explore Book Buy On Amazon

Once you know how to enter vectors and matrices in MATLAB, it’s time to see how to perform math using them. Adding and subtracting is a good place to start.

The essential rule when adding and subtracting vectors and matrices is that they must be the same size. You can’t add or subtract vectors or matrices of different sizes because MATLAB will display an error message. Use the following steps to see how to perform this task:

  1. Type a=[1,2;3,4] and press Enter.

    You see

    a =
      1  2
      3  4
  2. Type b=[5,6;7,8] and press Enter.

    You see

    b =
      5  6
      7  8
  3. Type c = a + b and press Enter.

    This step adds matrix a to matrix b. You see

    c =
      6  8
     10 12
  4. Type d = b - a and press Enter.

    This step subtracts matrix b from matrix a. You see

    d =
      4  4
      4  4
  5. Type e=[1,2,3;4,5,6] and press Enter.

    You see

    e =
      1  2  3
      4  5  6

    If you attempt to add or subtract matrix e from either matrix a or matrix b, you see an error message. However, the following step tries to perform the task anyway.

  6. Type f = e + a and press Enter.

    As expected, you see the following error message:

    Error using +
    Matrix dimensions must agree.

    The error messages differ a little between addition and subtraction, but the idea is the same. The matrices must be the same size in order to add or subtract them.

About This Article

This article is from the book:

About the book authors:

Jim Sizemore is professor of physics and engineering at Tyler Junior College. For over 25 years, Sizemore has worked in the semiconductor and software industries as a process engineer, device physicist, and software developer. John Paul Mueller has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: