logo

Creating Special Matrices in MATLAB 📂Programing

Creating Special Matrices in MATLAB

Zero Matrix

  • zeros(): Returns a zero matrix.
  • zeros(n): Returns a $n\times n$ zero matrix.
  • zeros(m,n): Returns a $n\times m$ zero matrix.
  • zeros(size(A)): Returns a zero matrix of the same size as matrix A.

Matrix with All Elements as 1

  • ones(): Returns a matrix where all elements are 1. However, for operations between two matrices, it’s more convenient to just use 1. It’s obvious that the code below is much simpler in the example code.
  • ones(n): Returns a $n\times n$ matrix where all elements are 1.
  • ones(m,n): Returns a $n\times m$ matrix where all elements are 1.
  • ones(size(A)): Returns a matrix of the same size as matrix A where all elements are 1.
A=[1 2 3; 4 -2 3; 5 3 7]

ones(size(A))./A
1./A

4.png

Identity Matrix

  • eye(): Returns the identity matrix.
  • eye(n): Returns a $n\times n$ identity matrix.
  • eye(m,n): Returns a $n\times m$ identity matrix.
  • eye([m,n]): Returns a $n\times m$ identity matrix where elements on the main diagonal are 1 and other elements are 0.
  • eye(n,'like',A): Returns a $n\times n$ identity matrix of the same data type as matrix A. If A is a complex matrix, it returns a complex identity matrix. If no size is specified, it returns a matrix of the same size as A.
eye([2,3])
eye(3,6)

A=[1+i 3-i]
eye(3, 'like', A)
eye(3,4 'like', A)

6.png

Random Numbers

  • rand(): Returns a random number between 0 and 1. The probability of each number being drawn is the same. The official Matlab website describes this as ‘uniformly distributed random numbers’.
  • rand(n): Returns a $n\times n$ matrix composed of random numbers between 0 and 1.
  • rand(m,n): Returns a $m\times n$ matrix composed of random numbers between 0 and 1.
  • rand(n,'like',A): Returns a $n\times n$ matrix composed of random numbers of the same data type as matrix A. If A is a complex matrix, it returns a complex matrix. If no size is specified, it returns a matrix of the same size as A.