Introduction to Vectors and Matrices in Matlab

Introduction to Vectors and Matrices in Matlab

As you know Matlab is the short form of Matrix Laboratory. As its name indicates, Matlab makes matrix and vector operations very easy. I am writing this tutorial on the assumption that you are familiar with Matlab, if not please goto the first tutorial.

Creating Row Matrix or Row Vector

Let’s start with a simple example for creating a row vector or row matrix with elements 1, 2, 3, 4, 5 and is assigned to a variable name A.

>> A = [1 2 3 4 5]
A =
1 2 3 4 5

In the above example we used equal sign (=) for assigning variable name, square brackets ([]) to enclose elements and space to separate ( ) elements. You can also use coma (,) for separating elements instead of space ( ).

Creating Column Matrix or Column Vector

Semicolon (;) is used to distinguish between rows and can define a colum vector in the following way.


>> A = [1;2;3]
A =
1
2
3

or you can write

>> A = [1
2
3]
A =
1
2
3

Transpose

Transpose of a matrix or a vector can be find using single quote (‘) as shown below.

>> A = [1 2 3]
A =
1 2 3

>> A'
ans =
1 
2 
3

 Defining a 3×3 Matrix

You can define a 3×3 matrix in any of the following ways.

>> A = [1 2 3; 4 5 6; 7 8 9]
>> A = [1 2 3
4 5 6
7 8 9]
>> A = [[1 4 7]' [2 5 8]' [3 6 9]']

All of the above command have same result as shown below.

A =
1 2 3
4 5 6
7 8 9

Defining Vectors with Repetitive Pattern

Matlab has a facility to create large vectors easily, which having elements with repetitive pattern by using colons (:). For example to create a vector whose first element is 1, second element is 2, third element is 3, up to 8 can be created by the following command.

>>  v = [1:8]
v =
1 2 3 4 5 6 7 8

If you wish to have repetitions with increment other than 1, then you have to specify starting number, increment and the last number as given below.

>> v = [1:2:8]
v =
1 3 5 7

Accessing Elements within a Vector or Matrix

Any element of a vector or matrix can be accessed through indexing as in every programming languages as shown below. Unlike C, C++ and Java, array index starts from 1.

>> a = [1 2 3 4];
>> a(3)
ans =
3
>> b = [1 2 3; 4 5 6; 7 8 9];
>> b(2,3)
ans =
6

Semicolon (;) is used to suppress output as described in the first tutorial.

Extracting Submatrices from a Matrix

Matlab also have the facility to extract submatrices from a matrix as shown in the below example.

>> A = [1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20];
A(2:4,1:3)
ans =
 6  7  8
11 12 13
16 17 18

This example creates a submatrix of matrix a containing elements of rows 2 to 4 and columns 1 to 3.

You can extract entire row or column in the following way.

>> A(:,2)
ans =
2
7
12
17
>> A(2,:)
ans =
6 7 8 9 10

Share this post


>