Matlab Matrix (original) (raw)

Last Updated : 7 Nov, 2025

A Matrix is a two-dimensional array of elements. In MATLAB (short for Matrix Laboratory), the matrix is created by assigning the array elements that are delimited by spaces or commas and using semicolons to mark the end of each row.

**Creating a Matrix in MATLAB

A matrix can be created by listing elements inside square brackets [ ].

**Syntax:

A = [elements; elements]

**Example: Creating a Matrix

MATLAB `

% Creating numeric and string matrices x = [1 2 3; 4 5 6; 7 8 9]; y = ['Geek'; 'Geek'];

`

**Output:

x =

1 2 3

4 5 6

7 8 9

y =

Geeks

Geeks

Finding the Size of a Matrix

You can find the dimensions (rows × columns) of a matrix using the size() function.

**Example:

MATLAB `

x = [1 2 3 4; 4 5 6 7; 7 8 9 10]; xSize = size(x)

y = ['Geeks'; 'Geeks']; ySize = size(y)

`

**Output:

xSize =

3 4

ySize =

2 5

Accessing Matrix Elements

To access specific elements, use the syntax:

matrix(row, column)

**Example 1: Access a Single Element

MATLAB `

x = [1 2 3 4; 4 5 6 7; 7 8 9 10]; x(3,2) % Access element in 3rd row, 2nd column

`

**Output:

ans =

8

**Example 2: Accessing Multiple Elements

To access multiple elements:

x = [1 2 3 4; 4 5 6 7; 7 8 9 10];

x(:, :)
x(1:2, :)
x(:, 2:end)
x(1:2, 2:3) % Elements from 2nd to 3rd column in first two rows

`

**Output:

ans =

1 2 3 4

4 5 6 7

7 8 9 10

ans =

1 2 3 4

4 5 6 7

ans =

2 3 4

5 6 7

8 9 10

ans =

2 3

5 6

Adding Elements or Dimensions

You can add rows or columns to a matrix using concatenation ([]) or the cat() function.

**Syntax:

cat(dimension, A, B, ...)

**Example 1: Using Brackets

Matlab `

x = [1 2 3 4; 4 5 6 7]; y = [7 8 9 10; 11 12 13 14];

a = [x; y]; % Add rows b = [x; 11 12 13 14]; % Add a new row x(:,5) = [15; 16]; % Add a column

`

**Output:

a =

1 2 3 4

4 5 6 7

7 8 9 10

11 12 13 14

b =

1 2 3 4

4 5 6 7

11 12 13 14

x =

1 2 3 4 15

4 5 6 7 16

**Example 2: Using cat()

MATLAB `

x = [1 2 3 4; 4 5 6 7]; y = [1 2 3 4; 4 5 6 7];

a = cat(1, x, y); % Add rows b = cat(2, x, y); % Add columns

`

**Output:

a =

1 2 3 4

4 5 6 7

1 2 3 4

4 5 6 7

b =

1 2 3 4 1 2 3 4

4 5 6 7 4 5 6 7

Deleting Rows or Columns

You can remove rows or columns by assigning them an empty array [].

**Example:

Matlab `

x = [1 2 3 4; 4 5 6 7; 7 8 9 10];

x(3,:) = []; % Delete 3rd row x(:,3) = []; % Delete 3rd column

`

Key Points