0
0
R Programmingprogramming~5 mins

Matrix dimensions in R Programming

Choose your learning style9 modes available
Introduction

Matrix dimensions tell you how many rows and columns a matrix has. This helps you understand its size and shape.

When you want to check the size of a matrix before doing calculations.
When you need to loop through rows or columns of a matrix.
When you want to make sure two matrices can be multiplied together.
When you want to reshape or modify a matrix based on its size.
Syntax
R Programming
dim(matrix_name)

The dim() function returns a vector with two numbers: number of rows and number of columns.

If the object is not a matrix or array, dim() may return NULL.

Examples
This creates a 2 by 3 matrix and then shows its dimensions.
R Programming
m <- matrix(1:6, nrow=2, ncol=3)
dim(m)
Here, the matrix has 3 rows and 3 columns (since 9 elements fill 3 columns automatically).
R Programming
m <- matrix(1:9, nrow=3)
dim(m)
A vector has no dimensions, so dim() returns NULL.
R Programming
v <- c(1,2,3)
dim(v)
Sample Program

This program creates a 3 by 4 matrix, gets its dimensions, and prints the number of rows and columns.

R Programming
m <- matrix(1:12, nrow=3, ncol=4)
d <- dim(m)
print(paste("Rows:", d[1]))
print(paste("Columns:", d[2]))
OutputSuccess
Important Notes

You can also use nrow() and ncol() to get rows and columns separately.

Knowing matrix dimensions helps avoid errors in matrix operations like multiplication.

Summary

Matrix dimensions tell you the number of rows and columns.

Use dim() to get both rows and columns at once.

Dimensions help you work safely with matrices in R.