(m1 <- matrix(1:9, 3, 3)) [,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
length(m1)[1] 9
The length() function works with matrices, but the results may not be that interesting.
Do: Explain what the value returned by length(m1) represents.
When applied to matrices, length() returns the number of cells in the matrix.
To get more useful information about the dimensions of the matrix, we use dim(), nrow(), or ncol().
As with vectors, default arithmetic with R matrices works element-wise. R performs the requested operation on each pair of corresponding entries in the two matrices.
[,1] [,2] [,3]
[1,] 4 5 4
[2,] -1 3 -4
[3,] 1 -2 -4
[,1] [,2] [,3]
[1,] 5 9 11
[2,] 1 8 4
[3,] 4 4 5
[,1] [,2] [,3]
[1,] 3 1 -3
[2,] -3 -2 -12
[3,] -2 -8 -13
[,1] [,2] [,3]
[1,] 0.25 0.800000 1.75
[2,] -2.00 1.666667 -2.00
[3,] 3.00 -3.000000 -2.25
[,1] [,2] [,3]
[1,] 4 20 28
[2,] -2 15 -32
[3,] 3 -12 -36
Use the three matrices defined below to answer this question.
[,1] [,2]
[1,] 2 2
[2,] 2 2
[,1] [,2]
[1,] 1 3
[2,] 2 4
[,1] [,2]
[1,] 6 6
[2,] 6 6
Given the above definitions of a, b, and c, predict what the following code will print.
Use the interactive editor to check your prediction.
R will apply the usual order-of-operations when doing element-wise arithmetic with matrices.
If you’re familiar with matrix algebra and/or have some affinity for programming languages that overload their operators, the matrix arithmetic described above may seem very strange. Rather than overloading the standard operators, R defines special functions for matrix algebraic operations. For example:
%*%: Multiplicationt(): Transpositionsolve(): Inversion [,1] [,2] [,3]
[1,] 7 3 -40
[2,] 11 9 -44
[3,] 15 15 -48
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[,1] [,2] [,3]
[1,] 0.161290323 -0.09677419 0.25806452
[2,] 0.064516129 0.16129032 -0.09677419
[3,] 0.008064516 -0.10483871 -0.13709677
myMat wherein each column is equal to the vector 1:5.myMat by \(\pi\) (i.e., the mathematical constant, “pi”).The built-in R object pi contains the value of \(\pi\).