lettura simple

Matrix of Ones in Matlab

In this lesson, I will explain how to create a matrix with all elements equal to one using the ones() function in Matlab.

ones(r,c)

The ones() function in Matlab has two parameters:

  • Number of rows (r)
    The first parameter is the number of rows in the matrix.
  • Number of columns (c)
    The second parameter is the number of columns in the matrix.

This function generates a matrix of ones (all-ones matrix).

Note. If you only specify the first parameter of the function (number of rows), Matlab will create a square matrix with the same number of rows and columns.

For example, you can create a 3x3 square matrix with three rows and three columns, composed of elements equal to 1, by manually typing:

>> M=[ 1 1 1 ; 1 1 1 ; 1 1 1 ]
M =
1 1 1
1 1 1
1 1 1

However, creating a matrix by specifying the value of each element can become cumbersome for large matrices.

In such cases, you can achieve the same result more efficiently using the ones() function.

For example, you can create the same 3x3 matrix as above by simply typing ones(3,3)

>> M=ones(3,3)
M =
1 1 1
1 1 1
1 1 1

If you only specify the first parameter (number of rows) of the ones() function, Matlab will create a square matrix with the same number of rows and columns.

So you could achieve the same result by typing ones(3)

>> M=ones(3)
M =
1 1 1
1 1 1
1 1 1

You can also create rectangular matrices using the ones() function.

For example, to create a 3x4 matrix with three rows and four columns, composed of elements equal to 1, you can type ones(3,4)

>> M=ones(3,4)
M =
1 1 1 1
1 1 1 1
1 1 1 1

The first parameter of the ones() function is the number of rows (3) of the matrix, while the second parameter indicates the number of columns (4) of the matrix.

This way, you can quickly create identity matrices of any shape and size in Matlab.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin