Home

How to Add and Subtract Vectors and Matrices in MATLAB

|
Updated:  
2016-03-26 08:22:32
|
From The Book:  
MATLAB For Dummies
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 author:

Jim Sizemore is Professor of Physics and Engineering at Tyler Junior College. For over 25 years he s worked in the semiconductor and software industries as a process engineer, device physicist, and software developer and has been teaching college physics, engineering, and math for the last 13 years.

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.