How to Create a Matrix in MATLAB?
In this article, we will guide you through the process of creating a matrix step by step, whether you are a beginner or already have some experience with MATLAB. Creating a matrix allows you to organize and structure data conveniently and efficiently, enabling you to perform various operations and analyses on the data.
How to Create a Matrix in MATLAB?
MATLAB facilitates us with multiple methods to create a matrix, some of these methods are given below:
- Using the zeros() Function
- Using the ones() function
- Using the magic() function
- Using the eye() function
- Using the rand() function
All these methods are MATLAB built-in functions used for creating a matrix. Now we will explore all these functions to create a matrix in MATLAB.
1: Using zeros() Function
The zeros() is a built-in MATLAB function used for creating a matrix of any size having all zero elements.
For example, the following example will create a matrix of size 2×3 consisting of zeros elements in MATLAB.
2: Using ones() Function
The MATLAB users can also use the ones() function to create a matrix of any size having all 1’s elements. For example, the 5×3 matrix having all elements equal to the number 1 will be created using the code below.
3: Using magic() Function
The MATLAB built-in magic() function can also be used to create a square matrix of size n having all elements lying between 1 and n power 2. Where n should be greater or equal to 3.
For example, the following code will create a 3×3 square matrix in MATLAB.
4: Using eye() Function
The eye() is a built-in function in MATLAB that allows us to create a square identity matrix of size n having all diagonal elements 1’s and non-diagonal zeros. For example:
5: Using rand() Function
The rand() is a built-in function in MATLAB that allows us to create a matrix of any specified size having all random numbers lying between 0 and 1.
For example, using the below-given code, you will be able to create a matrix of 3×4 size consisting of random numbers.
Conclusion
Matrices are the building blocks of MATLAB and can be created using MATLAB built-in functions including zeros(), ones(), magic(), eye(), and rand(). All these functions are used for creating a matrix having different elements according to their functionalities. This tutorial discussed how to create a matrix in MATLAB using several examples.
Source: linuxhint.com