| MATLAB® | ![]() |
| On this page… |
|---|
The most basic MATLAB® data structure is the matrix: a two-dimensional, rectangularly shaped data structure capable of storing multiple elements of data in an easily accessible format. These data elements can be numbers, characters, logical states of true or false, or even other MATLAB structure types. MATLAB uses these two-dimensional matrices to store single numbers and linear series of numbers as well. In these cases, the dimensions are 1-by-1 and 1-by-n respectively, where n is the length of the numeric series. MATLAB also supports data structures that have more than two dimensions. These data structures are referred to as arrays in the MATLAB documentation.
MATLAB is a matrix-based computing environment. All of the data that you enter into MATLAB is stored in the form of a matrix or a multidimensional array. Even a single numeric value like 100 is stored as a matrix (in this case, a matrix having dimensions 1-by-1):
A = 100; whos A Name Size Bytes Class A 1x1 8 double array
Regardless of the class being used, whether it is numeric, character, or logical true or false data, MATLAB stores this data in matrix (or array) form. For example, the string 'Hello World' is a 1-by-11 matrix of individual character elements in MATLAB. You can also build matrices composed of more complex classes, such as MATLAB structures and cell arrays.
To create a matrix of basic data elements such as numbers or characters, see
To build a matrix composed of other matrices, see
This section also describes
The simplest way to create a matrix in MATLAB is to use the matrix constructor operator, []. Create a row in the matrix by entering elements (shown as E below) within the brackets. Separate each element with a comma or space:
row = [E1, E2, ..., Em] row = [E1 E2 ... Em]
For example, to create a one row matrix of five elements, type
A = [12 62 93 -8 22];
To start a new row, terminate the current row with a semicolon:
A = [row1; row2; ...; rown]
This example constructs a 3 row, 5 column (or 3-by-5) matrix of numbers. Note that all rows must have the same number of elements:
A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6]
A =
12 62 93 -8 22
16 2 87 43 91
-4 17 -72 95 6
The square brackets operator constructs two-dimensional matrices only, (including 0-by-0, 1-by-1, and 1-by-n matrices). To construct arrays of more than two dimensions, see Creating Multidimensional Arrays.
For instructions on how to read or overwrite any matrix element, see Matrix Indexing.
When entering signed numbers into a matrix, make sure that the sign immediately precedes the numeric value. Note that while the following two expressions are equivalent,
7 -2 +5 7 - 2 + 5
ans = ans =
10 10
the next two are not:
[7 -2 +5] [7 - 2 + 5]
ans = ans =
7 -2 5 10
MATLAB has a number of functions that create different kinds of matrices. Some create specialized matrices like the Hankel or Vandermonde matrix. The functions shown in the table below create matrices for more general use.
Function | Description |
|---|---|
Create a matrix or array of all ones. | |
Create a matrix or array of all zeros. | |
Create a matrix with ones on the diagonal and zeros elsewhere. | |
Distribute elements of an input matrix to specified locations in an output matrix, also allowing for accumulation. | |
Create a diagonal matrix from a vector. | |
Create a square matrix with rows, columns, and diagonals that add up to the same number. | |
Create a matrix or array of uniformly distributed random numbers. | |
Create a matrix or array of normally distributed random numbers and arrays. | |
Create a vector (1-by-n matrix) containing a random permutation of the specified integers. |
Most of these functions return matrices of type double (double-precision floating point). However, you can easily build basic arrays of any numeric type using the ones, zeros, and eye functions.
To do this, specify the MATLAB class name as the last argument:
A = zeros(4, 6, 'uint32')
A =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Here are some examples of how you can use these functions.
Creating a Magic Square Matrix. A magic square is a matrix in which the sum of the elements in each column, or each row, or each main diagonal is the same. To create a 5-by-5 magic square matrix, use the magic function as shown.
A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Note that the elements of each row, each column, and each main diagonal add up to the same value: 65.
Creating a Random Matrix. The rand function creates a matrix or array with elements uniformly distributed between zero and one. This example multiplies each element by 20:
A = rand(5) * 20
A =
19.0026 15.2419 12.3086 8.1141 1.1578
4.6228 9.1294 15.8387 18.7094 7.0574
12.1369 0.3701 18.4363 18.3381 16.2633
9.7196 16.4281 14.7641 8.2054 0.1972
17.8260 8.8941 3.5253 17.8730 2.7778
The sequence of numbers produced by rand is determined by the internal state of the generator. Setting the generator to the same fixed state enables you to repeat computations. Examples in this documentation that use the rand function are initialized to a state of 0 to make the output consistent each time they are run:
rand('state', 0);
Creating a Diagonal Matrix. Use diag to create a diagonal matrix from a vector. You can place the vector along the main diagonal of the matrix, or on a diagonal that is above or below the main one, as shown here. The -1 input places the vector one row below the main diagonal:
A = [12 62 93 -8 22];
B = diag(A, -1)
B =
0 0 0 0 0 0
12 0 0 0 0 0
0 62 0 0 0 0
0 0 93 0 0 0
0 0 0 -8 0 0
0 0 0 0 22 0
Matrix concatenation is the process of joining one or more matrices to make a new matrix. The brackets [] operator discussed earlier in this section serves not only as a matrix constructor, but also as the MATLAB concatenation operator. The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A; B] vertically concatenates them.
This example constructs a new matrix C by concatenating matrices A and B in a vertical direction:
A = ones(2, 5) * 6; % 2-by-5 matrix of 6's
B = rand(3, 5); % 3-by-5 matrix of random values
C = [A; B] % Vertically concatenate A and B
C =
6.0000 6.0000 6.0000 6.0000 6.0000
6.0000 6.0000 6.0000 6.0000 6.0000
0.9501 0.4860 0.4565 0.4447 0.9218
0.2311 0.8913 0.0185 0.6154 0.7382
0.6068 0.7621 0.8214 0.7919 0.1763
You can construct matrices, or even multidimensional arrays, using concatenation as long as the resulting matrix does not have an irregular shape (as in the second illustration shown below). If you are building a matrix horizontally, then each component matrix must have the same number of rows. When building vertically, each component must have the same number of columns.
This diagram shows two matrices of the same height (i.e., same number of rows) being combined horizontally to form a new matrix.

The next diagram illustrates an attempt to horizontally combine two matrices of unequal height. MATLAB does not allow this.

The following functions combine existing matrices to form a new matrix.
Function | Description |
|---|---|
Concatenate matrices along the specified dimension | |
Horizontally concatenate matrices | |
Vertically concatenate matrices | |
Create a new matrix by replicating and tiling existing matrices | |
Create a block diagonal matrix from existing matrices |
Here are some examples of how you can use these functions.
Concatenating Matrices and Arrays. An alternative to using the [] operator for concatenation are the three functions cat, horzcat, and vertcat. With these functions, you can construct matrices (or multidimensional arrays) along a specified dimension. Either of the following commands accomplish the same task as the command C = [A; B] used in the section on Concatenating Matrices:
C = cat(1, A, B); % Concatenate along the first dimension C = vertcat(A, B); % Concatenate vertically
Replicating a Matrix. Use the repmat function to create a matrix composed of copies of an existing matrix. When you enter
repmat(M, v, h)
MATLAB replicates input matrix M v times vertically and h times horizontally. For example, to replicate existing matrix A into a new matrix B, use
A = [8 1 6; 3 5 7; 4 9 2] A = 8 1 6 3 5 7 4 9 2 B = repmat(A, 2, 4) B = 8 1 6 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2 8 1 6 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2
Creating a Block Diagonal Matrix. The blkdiag function combines matrices in a diagonal direction, creating what is called a block diagonal matrix. All other elements of the newly created matrix are set to zero:
A = magic(3); B = [-5 -6 -9; -4 -4 -2]; C = eye(2) * 8; D = blkdiag(A, B, C) D = 8 1 6 0 0 0 0 0 3 5 7 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 -5 -6 -9 0 0 0 0 0 -4 -4 -2 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 8
Because numeric sequences can often be useful in constructing and indexing into matrices and arrays, MATLAB provides a special operator to assist in creating them.
This section covers
The colon operator (first:last) generates a 1-by-n matrix (or vector) of sequential numbers from the first value to the last. The default sequence is made up of incremental values, each 1 greater than the previous one:
A = 10:15
A =
10 11 12 13 14 15
The numeric sequence does not have to be made up of positive integers. It can include negative numbers and fractional numbers as well:
A = -2.5:2.5 A = -2.5000 -1.5000 -0.5000 0.5000 1.5000 2.5000
By default, MATLAB always increments by exactly 1 when creating the sequence, even if the ending value is not an integral distance from the start:
A = 1:6.3
A =
1 2 3 4 5 6
Also, the default series generated by the colon operator always increments rather than decrementing. The operation shown in this example attempts to increment from 9 to 1 and thus MATLAB returns an empty matrix:
A = 9:1 A = Empty matrix: 1-by-0
The next section explains how to generate a nondefault numeric series.
To generate a series that does not use the default of incrementing by 1, specify an additional value with the colon operator (first:step:last). In between the starting and ending value is a step value that tells MATLAB how much to increment (or decrement, if step is negative) between each number it generates.
To generate a series of numbers from 10 to 50, incrementing by 5, use
A = 10:5:50
A =
10 15 20 25 30 35 40 45 50
You can increment by noninteger values. This example increments by 0.2:
A = 3:0.2:3.8
A =
3.0000 3.2000 3.4000 3.6000 3.8000
To create a sequence with a decrementing interval, specify a negative step value:
A = 9:-1:1
A =
9 8 7 6 5 4 3 2 1
Matrices and arrays can be composed of elements of most any MATLAB data type as long as all elements in the matrix are of the same type. If you do include elements of unlike classes when constructing a matrix, MATLAB converts some elements so that all elements of the resulting matrix are of the same type. (See Built-In Classes (Data Types) for information on any of the MATLAB classes discussed here.)
Data type conversion is done with respect to a preset precedence of classes. The following table shows the five classes you can concatenate with an unlike type without generating an error (that is, with the exception of character and logical).
TYPE | character | integer | single | double | logical |
|---|---|---|---|---|---|
character | character | character | character | character | invalid |
integer | character | integer | integer | integer | integer |
single | character | integer | single | single | single |
double | character | integer | single | double | double |
logical | invalid | integer | single | double | logical |
For example, concatenating a double and single matrix always yields a matrix of type single. MATLAB converts the double element to single to accomplish this.
If you combine different integer types in a matrix (e.g., signed with unsigned, or 8-bit integers with 16-bit integers), MATLAB returns a matrix in which all elements are of one common type. MATLAB sets all elements of the resulting matrix to the data type of the left-most element in the input matrix. For example, the result of the following concatenation is a vector of three 16-bit signed integers:
A = [int16(450) uint8(250) int32(1000000)]
MATLAB also displays a warning to inform you that the result may not be what you had expected:
A = [int16(450) uint8(250) int32(1000000)]; Warning: Concatenation with dominant (left-most) integer class may overflow other operands on conversion to return class.
You can disable this warning by entering the following two commands directly after the operation that caused the warning. The first command retrieves the message identifier associated with the most recent warning issued by MATLAB. The second command uses this identifier to disable any further warnings of that type from being issued:
[msg, intcat_msgid] = lastwarn;
warning('off', intcat_msgid);
To reenable the warning so that it will now be displayed, use
warning('on', intcat_msgid);
You can use these commands to disable or enable the display of any MATLAB warning.
Example of Combining Unlike Integer Sizes. After disabling the integer concatenation warnings as shown above, concatenate the following two numbers once, and then switch their order. The return value depends on the order in which the integers are concatenated. The left-most type determines the data type for all elements in the vector:
A = [int16(5000) int8(50)] A = 5000 50 B = [int8(50) int16(5000)] B = 50 127
The first operation returns a vector of 16-bit integers. The second returns a vector of 8-bit integers. The element int16(5000) is set to 127, the maximum value for an 8-bit signed integer.
The same rules apply to vertical concatenation:
C = [int8(50); int16(5000)]
C =
50
127
Note You can find the maximum or minimum values for any MATLAB integer type using the intmax and intmin functions. For floating-point types, use realmax and realmin. |
Example of Combining Signed with Unsigned. Now do the same exercise with signed and unsigned integers. Again, the left-most element determines the data type for all elements in the resulting matrix:
A = [int8(-100) uint8(100)] A = -100 100 B = [uint8(100) int8(-100)] B = 100 0
The element int8(-100) is set to zero because it is no longer signed.
MATLAB evaluates each element prior to concatenating them into a combined array. In other words, the following statement evaluates to an 8-bit signed integer (equal to 50) and an 8-bit unsigned integer (unsigned -50 is set to zero) before the two elements are combined. Following the concatenation, the second element retains its zero value but takes on the unsigned int8 type:
A = [int8(50), uint8(-50)] A = 50 0
If you combine integers with double, single, or logical classes, all elements of the resulting matrix are given the data type of the left-most integer. For example, all elements of the following vector are set to int32:
A = [true pi int32(1000000) single(17.32) uint8(250)]
If you construct a matrix using empty matrix elements, the empty matrices are ignored in the resulting matrix:
A = [5.36; 7.01; []; 9.44]
A =
5.3600
7.0100
9.4400
Here are some examples of data type conversion during matrix construction.
Combining Single and Double Types. Combining single values with double values yields a single matrix. Note that 5.73*10^300 is too big to be stored as a single, thus the conversion from double to single sets it to infinity. (The class function used in this example returns the data type for the input value):
x = [single(4.5) single(-2.8) pi 5.73*10^300]
x =
4.5000 -2.8000 3.1416 Inf
class(x) % Display the data type of x
ans =
single
Combining Integer and Double Types. Combining integer values with double values yields an integer matrix. Note that the fractional part of pi is rounded to the nearest integer. (The int8 function used in this example converts its numeric argument to an 8-bit integer):
x = [int8(21) int8(-22) int8(23) pi 45/6]
x =
21 -22 23 3 7
class(x)
ans =
int8
Combining Character and Double Types. Combining character values with double values yields a character matrix. MATLAB converts the double elements in this example to their character equivalents:
x = ['A' 'B' 'C' 68 69 70] x = ABCDEF class(x) ans = char
Combining Logical and Double Types. Combining logical values with double values yields a double matrix. MATLAB converts the logical true and false elements in this example to double:
x = [true false false pi sqrt(7)]
x =
1.0000 0 0 3.1416 2.6458
class(x)
ans =
double
![]() | Matrices and Arrays | Matrix Indexing | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |