# Matlab-Matrix - Create a Matrix

#### Artificial Neural Network and Machine Learning using MATLAB

54 Lectures 4 hours

#### Machine Learning for Data Science using MATLAB

Featured

62 Lectures 9 hours

In MATLAB, you can create a matrix by entering the elements in each row as comma. You can also create a matrix with space delimited numbers and by using the semicolons to mark the end of each row.

## Matrix with single row

Let us create a simple matrix in MATLAB that has a single row and three elements. Each element should have a space or comma.

### Example

Consider the below mentioned elements to create a matrix.

```m=[2, 4, 6]
```

### Output

On execution in MATLAB it will display the following −

```>>m = [2, 4, 6]

m =

2  4  6
>>
```

When you execute the code in MATLAB, the result of the matrix is displayed in the command window.

## Matrix with Multiple rows

### Example

Let us now create a matrix with multiple rows. To do that, we need to separate each row with semicolon (;) as shown below −

```m = [2 4 6; 3 6 9; 4 8 12]
```

### Output

Here 2 4 6 is the first row, 3 6 9 is the second row and 4 8 12 is the third row. The matrix will be as follows −

```m = 2  4  6
3  6  9
4  8 12
```

Let us now execute the same in MATLAB command prompt, as mentioned below −

```>> m = [2 4 6; 3 6 9; 4 8 12]

m =

2  4  6
3  6  9
4  8 12

>>
```

The 3x3 matrix is displayed as shown above in MATLAB.

Besides creating matrix with the values of your choice you can also make use of the built-in MATLAB functions zeros, rand or ones to create a matrix as shown below −

### The zerosfunctions

This will create matrix with all zeros with the given row/column size.

Example

You can use MATLAB zeros function as follows −

```m0 = zeros(3,3)
```

Output

You will get the following output −

```>> m0 = zeros(3,3)

m0 =

0  0  0
0  0  0
0  0  0

>>
```

### The onesfunction

The matrix created will have ones as the values.

Example

You can use MATLAB ones function as follows −

```m1 = ones(3,3)
```

Output

You will get the following output −

```>> m1 = ones(3,3)

m1 =
1  1  1
1  1  1
1  1  1

>>
```

### The rand() function

The function rand() allows you to create a matrix with random elements for the size given. Here is an example for the same.

Example

```m1 = rand(3,3)
```

Output

Let us now execute the same in MATLAB to see the results. The output is as follows −

```>> m1 = rand(3,3)

m1 =

0.8147  0.9134  0.2785
0.9058  0.6324  0.5469
0.1270  0.0975  0.9575

>>
```