0
0
R Programmingprogramming~10 mins

Matrix dimensions in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Matrix dimensions
Create Matrix
Check Dimensions
Use dim() Function
Get Rows and Columns
Use Dimensions in Code
This flow shows how to create a matrix, check its dimensions using dim(), and then use those dimensions in your code.
Execution Sample
R Programming
m <- matrix(1:6, nrow=2, ncol=3)
dim(m)
Create a 2x3 matrix and get its dimensions.
Execution Table
StepActionCodeResult
1Create matrix m with values 1 to 6, 2 rows, 3 columnsm <- matrix(1:6, nrow=2, ncol=3)m = [ [1, 3, 5], [2, 4, 6] ]
2Get dimensions of matrix mdim(m)2 3
3Use dimensions to get number of rowsnrow(m)2
4Use dimensions to get number of columnsncol(m)3
💡 All steps complete, matrix dimensions retrieved successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
mNULL[[1, 3, 5], [2, 4, 6]][[1, 3, 5], [2, 4, 6]][[1, 3, 5], [2, 4, 6]][[1, 3, 5], [2, 4, 6]]
dim(m)NULLNULL[2, 3][2, 3][2, 3]
nrow(m)NULLNULLNULL22
ncol(m)NULLNULLNULLNULL3
Key Moments - 2 Insights
Why does dim(m) return a vector with two numbers?
dim(m) returns two numbers because it gives the number of rows first, then the number of columns, as shown in step 2 of the execution_table.
Is the matrix filled by rows or columns when created with matrix(1:6, nrow=2, ncol=3)?
By default, R fills the matrix by columns, so numbers go down each column first, as seen in the matrix m after step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of dim(m) at step 2?
A[2, 3]
B[3, 2]
C[6]
DNULL
💡 Hint
Check the 'Result' column in row for step 2 in execution_table.
At which step do we get the number of rows of the matrix?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column describing getting number of rows.
If we change nrow=3 and ncol=2 in matrix creation, what will dim(m) return?
A[2, 3]
B[3, 2]
C[6, 1]
D[1, 6]
💡 Hint
dim(m) returns rows then columns, so changing nrow and ncol swaps those values.
Concept Snapshot
Matrix dimensions in R:
- Use matrix(data, nrow, ncol) to create.
- Use dim(matrix) to get rows and columns as a vector.
- Use nrow(matrix) and ncol(matrix) for separate values.
- R fills matrices by columns by default.
Full Transcript
This visual execution shows how to create a matrix in R with specific rows and columns, then how to get its dimensions using dim(). The matrix m is created with values 1 to 6, arranged in 2 rows and 3 columns. The dim() function returns a vector with two numbers: the number of rows and the number of columns. We also see how to get the number of rows and columns separately using nrow() and ncol(). This helps understand how matrix dimensions work in R.