Matrices: Matrices in MATLAB
Basic properties and creation of matrices
Matrices are in MATLAB two-dimensional arrays. You can think of a structure of row vectors of equal length which are placed under each other.
>> A = [1 2 3; 4 5 6] % explicit entering of matrix elements
A =
1 2 3
4 5 6
>> A = [1:3; 4:6] % iterations used for the rows in the matrix
A =
1 2 3
4 5 6
>> dimension = size(A)
dimension =
2 3
\(\phantom{x}\)
We illustrate other commonly used methods for creating arrays with examples.
Construction of a matrix by repetition loops
>> A = zeros(3,4); % zero matrix to reserve storage space
>> for i = 1:3
for j = 1:4
A(i,j) = i^j % definition of a matrix entry
end
end
>> A
A =
1 1 1 1
2 4 8 16
3 9 27 81
Construction of a matrix via an indexing function
>> i = (1:3)'; j = 1:4; fun = @(a,b) a.^b;
>> A = bsxfun(fun, i, j)
A =
1 1 1 1
2 4 8 16
3 9 27 81
Construction of a special matrix There are also special functions to create matrices and vectors with ones and zeros, namely zeros
,
eye
and ones,
and to create diagonal matrices, namely diag
:
>> Z = zeros(2,4) % zero matrix
Z =
0 0 0 0
0 0 0 0
>> I = eye(3) % identity matrix
I =
1 0 0
0 1 0
0 0 1
>> J = ones(3,3) % matrix with ones
J =
1 1 1
1 1 1
1 1 1
>> diag([1 2 3]) % diagonal matrix
ans =
1 0 0
0 2 0
0 0 3
Construction of a matrix by stacking Arrays can also be stacked horizontally and vertically:
>> [AI] % horizontal stacking of matrices
ans =
1 1 1 1 1 0 0
2 4 8 16 0 1 0
3 9 27 81 0 0 1
> [Z; A; Z] % vertical stacking matrices
ans =
0 0 0 0
0 0 0 0
1 1 1 1
2 4 8 16
3 9 27 81
0 0 0 0
0 0 0 0
Construction of a random matrix You can create randomly generated matrices.
>> A = rand(3,2) % random 3x2 matrix with numbers between 0 an 1
A =
0.7922 0.0357
0.9595 0.8491
0.6557 0.9340
>> A = randi([5,8], 2, 3) % random 2x3 matrix with integers in segment [5, 8]
A =
6 8 5
7 8 8
Construction of a regular grid We discuss two special MATLAB functions to create vectors and arrays, namely linspace
and meshgrid
. We will use these functions a lot in plotting graphs and surfaces. If you want an array of \(N\) equidistant values in the interval \((a,b)\), do it then with the function linspace(a,b,N)
:
>> x = linspace(0,2,5)
x =
0 0.5000 1.0000 1.5000 2.0000
>> y = linspace(0,1,3)
y =
0 0.5000 1.0000
These arrays can be used to define a two-dimensional grid and to store \(x\) - and \(y\) coordinates of all grid points.
>> [X, Y] = meshgrid(x, y);
>> X
X =
0 0.5000 1.0000 1.5000 2.0000
0 0.5000 1.0000 1.5000 2.0000
0 0.5000 1.0000 1.5000 2.0000
>> Y
Y =
0 0 0 0 0
0.5000 0.5000 0.5000 0.5000 0.5000
1.0000 1.0000 1.0000 1.0000 1.0000