Arrays in Matlab

Matlab → Basics → Variables → Functions → Arrays

We usually need a list of numbers to manipulate data. An array is a list of numbers arranged in rows or columns. The simplest array (also called vector) is a single row or column of numbers. It is also called one-dimensional array. And a two-dimensional array (also called matrix) has numbers in both rows and columns.

A single row array A with numbers 3, 5, and 7 can be created in Matlab as,

>> A=[3 5 7]
A =
3 5 7

And a single column array B with numbers 4, -10, and 17 can be created in Matlab as,

>> B=[4; -10; 17]
B =
4
-10
17

The next Table shows some more examples of arrays.

Command Answer
>> A=[2 5 9] A = 2 5 9
>> B=[2;5;9] B =
2
5
9
>> C=[1 2 3;4 5 6] C =
1 2 3
4 5 6
>> D=[4 1 2 3 4 5; 6 7 8 9 0 1] D =
4 1 2 3 4 5
6 7 8 9 0 1
>> E=[5 9 0 13 4; 7 11 9 0 2; 7 8 9 0 10] E =
5 9 0 13 4
7 11 9 0 2
7 8 9 0 10

Creating vectors with equal spacing
Vectors (or one-dimensional arrays) with equal spacing can also be created. The general formulas for creating equally spaced vectors are:

VectorName = a:b Create a vector from a to b with step size 1.
VectorName = a:b:c Create a vector from a to c with step size b.

Consider the next example where first we will create a vector from 5 to 15 with step size 1, and then a vector from 1 to 22 with step size 3.

>> A=5:15
A =
5 6 7 8 9 10 11 12 13 14 15

>> B=1:3:22
B =
1 4 7 10 13 16 19 22

Equally spaced vectors with total number of elements can also be created using the linspace command. The general formula in this case is

VectorName = linspace(a,b,n)

Where a is the first element, b is the last element, and n is the total number of elements. The following example creates a vector from 1 to 10 where total number of elements are 6, and Table 7.6 shows some more examples of equally spaced vectors.

>> Z=linspace(1,10,6)
Z =
1.0000 2.8000 4.6000 6.4000 8.2000 10.0000

The next Table shows some more examples of equally spaced vectors.

Command Description Answer
>> x=1:10 Create a vector ‘x’ from 1 to 10 with step size 1. 1 2 3 4 5 6 7 8 9 10
>> y=1:2:11 Create a vector ‘y’ from 1 to 11 with step size 2. 1 3 5 7 9 11
>> z=2:3:14 Create a vector ‘z’ from 2 to 14 with step size 3. 2 5 8 11 14
>> x=linspace(1,10,4) Create a vector ‘x’ from 1 to 10 where total elements are 4. 1 4 7 10
>> y=linspace(1,10,5) Create a vector ‘y’ from 1 to 10 where total elements are 5. 1.0000 3.2500 5.5000 7.7500 10.0000
>> z=linspace(1,20,4) Create a vector ‘z’ from 1 to 20 where total elements are 4. 1.0000 7.3333 13.6667 20.0000