Find a Guide

Matrices in MATLAB

Introduction

In MATLAB, data can be stored in one direction - this is called a vector, or array. We can also store data in two directions - this is called a matrix! Matrices have very similar notation as arrays, but they have some key differences. Let's get learning!

Creating Matrices

Matrices can be defined in a few ways, let's take a look.

matlab

mat1 = [1, 2; 3, 4];

mat2 = [5 6; 7 8];

mat3 = [ 9  10
               11 12 ];

Similar with arrays, each row value can be separated by either a space or a comma, and to start a new row, a semicolon can be used. Notice for mat3, we could manually go to a new line as well to start a new row. Matrices, like mentioned before, are 2-dimensional, which means they span in two directions. One direction is a row, which runs horizontally (left to right) and the other is a column, which runs vertically (top to bottom).

Like arrays, matrices can be defined using multiple value types, but depending on which types are used, different things will happen.

matlab

% mat4 = ["hello" 3; true 'char'];
% This will error!

mat5 = ["hello" 3; true "char"];
% This will create a matrix full of strings

For mat4, if we tried defining this matrix, it would error because there is a boolean and character array value entered and MATLAB cannot convert a boolean to a character array and vice versa. With mat5, since there is a string present, MATLAB will convert all values into strings to keep the consistency. Note: always do some testing before mixing different variable types in matrices to make sure you get the expected outcome!

Editing Matrices

To edit matrices, we will use a similar notation to editing arrays. Let's say we have a 3 by 3 matrix (3 rows and 3 columns), and we wanted to change the value on the second row, third column. We could do that as so:

matlab

mat6 = [ 9 2 4
               5 3 7
               8 1 6 ];

mat6(2,3) = 0;

Using this notation, we changed the value on the second row, third column of mat6 to be zero, so now $ mat6 = \begin{bmatrix} 9 & 2 & 4 \\ 5 & 3 & 0 \\ 8 & 1 & 6 \end{bmatrix} $.

Array Concat

We can also make matrices using array concatenation. Given a few row or column arrays, we can concatenate them together to form matrices.

matlab

arr1 = [1 2 3];
arr2 = [4 5 6];

mat7 = [arr1; arr2];
% output: [ 1 2 3
%                4 5 6 ]

What we did above was we took two horizontal vectors, arr1 and arr2, and we used them to form the matrix mat7. Each vector will act as a row in mat7 and we start a new row by using the semicolon operator. Now, what if we use a comma instead?

matlab

% from before
arr1 = [1 2 3];
arr2 = [4 5 6];

mat7 = [arr1, arr2];
% output: [ 1 2 3 4 5 6 ]

Since we used a comma instead, we continued adding arr2 to arr1 to form a 1 by 6 vector stored in mat7. This is a handy tool to keep in the toolbox!

Find a Guide