Applications of Matrices in MATLAB

Matrices are an essential topic in different fields of study, especially in mathematics, where you have a bulk of data and want to organize, relate, transfer, and perform different operations on data in a better manner. We have studied a lot of types and operations on the matrices and have worked on different types with the help of MATLAB. Today, we are here to present the applications of the matrices in different fields of study to clarify the importance of this topic. So, have a look at the list of topics we are going to learn. Yet, first of all, I am going to describe what a matrix is.

What is a Matrix?

In the fields of physics and mathematics, there is the use of different types of numbers in groups of various types. In order to organize the data into a manageable format, matrices are used. A matrix is a rectangular array of numbers that are enclosed by a square matrix (or, in some cases, parentheses). 

The information about the numbers of rows and columns is called the order of matrices, and on the basis of this information, we can recognize different types of matrices. The types, in turn, are used in different applications because of their unique behavior. By changing the order of the matrix, the properties and working of the matrices changes according to the changes. Mostly, square matrices are used in different applications.

It is interesting to know that in the early days of matrices, these were considered arrays. With the passage of time, when they were involved more and more in different research and methodologies, matrices gained popularity. Because of the ease of usage, this popularity is not going to end. So, have a look at the different types of fields where matrices are used in different ways but before going into details, you must know, these fields are not only dependent on the matrices but the normal functioning of these fields include the usage of matrices in different ways. 

Applications of Matrices

As we have said earlier, matrices are used to deal with massive amounts of data better. The matrices that we have learned and seen till now are of very minimum order, and these are kept simple for the better concepts in easy ways, but in practice, we have seen that there are gigantic matrices with complex data in them, and at that point, it is difficult to solve and save them manually. Have a look at the different fields of practical life where matrices are used in a routine.

Matrices in Cryptography 

Data cryptography is an important department in data communication in which the encryption of the data is an important process. It is done by using different keys and codes to secure the message and communication in a better way. A large amount of data is sent and received by different parties, and the encryption techniques also require some other space as well. Matrixes are used to make sure that all the data and its codes are stored in a better way. These matrices 

save the keys of the encrypted data to decrypt them on the receiving end and in this way, matrices play a key role in cryptography.

Use of Matrices in Wireless Communication

We all know that in wireless communication, usually air is used as the medium to send and receive messages from one point to the other. In this process, matrices are used to detect, extract, and process the information about the message that is to be delivered. Here are some other uses of matrices in this department:

Signal estimation and the detection of the problem during communication are done with the help of matrices. 

  • Sensor array signal processing involves the matrices.

  • In the processing and representation of a digital image, matrices have a great role. 

  • Radar signals

  • Underwater surveillance

With the help of matrices, wireless communication is done efficiently, and understanding the code becomes easy. Think about the case if the data of different queries are not used in the form of a matrix, then finding the data of a simple command would never be organized. 

Matrices in Mathematics

The use of matrices in the field of mathematics is not new to us. We all know that it is a basic concept in mathematics and a great variety of concepts of matrices are used in different ways while solving mathematical problems. One of the major use in mathematics is a solution of linear equations with the help of matrices. The complex and time taking equations can be easily solved with the help of rules of matrices in different ways. 

In engineering and other related fields of mathematics, matrices are the basic concepts and it is used in different ways to make the working of the system better manner. We have seen different cases in which the matrix is used as the alternative method to find the unknown value because it is a more organized way and the great number of research resulted in different theorems and laws therefore, the long calculations are minimized to their result by simply using the theorems.

Matrices in Computer Graphics

One of the amazing applications of matrices is in the form of computer graphics where the pictures and the graphics comprise pixels and the array of these pixels and points are arranged in the form of matrices for easy transformation and working. Overall, you can say that in computer graphics, each digital image is treated as a matrix. Therefore, different types of operations used in the matrices are applied to the graphics with great ease. Not only in the dimensions and the sizes but also for the colors of the images, matrices are used to store and reuse the values for the images and graphics. For example, in the CNN technique, different types of matrices are used. For the greyscale image, only a 2D image is used and if one wants to get the RBG system image, there is a need for a 3D matrix. 

Three Dimensional Games and Matrices

Gaming is one of the most important filed in graphics and when we talk about three-dimensional games, matrices are important there in order to alter the 3D space in different ways. For this purpose, if we use simple words, the conversions between the 2D and 3D matrices are used by different techniques, and therefore, we get the final output. Moreover, the quality of the result depends upon the way you use the data in different ways. 

Matrices and Geology

During the seismic survey in geology, matrices are used in a great way. For real-time surveys of different areas of common real problems such as mortality rate, population, the number of people in different areas of the world, and other specific counting related to real-life problems involve the use of matrices because it becomes easy to deal with great data using different operations on the data.

The Matrices in the Field of IT

In different Information technology organizations, matrices are used to execute and search the different queries. The IT security system needs to have a secure way to deal with all the information and once saved, data is to be retrieved in an efficient way with the help of minimum commands. If the data is not present in the form of tables, or we should say, in the form of matrices, organizing, storing, retrieving, and dealing with the data will be like a nightmare. 

Using Matrices to Find the Collinear Points

It is one of the procedures in mathematics in which the values of collinear points are found with the help of matrices. If it seems simple at this time then you should think of the case where gigantic collinear points are found with the help of matrics with the help of different software and these points are in return used in different ways. 

Pre-allocation of Matrices in MATLAB

As we have said, matrices make the working of daily life data and complex calculations easy. We read different types of commands about the matrices when we were learning about their functioning and therefore, we can now use them in a simple program to prepare the code in which the matrix is used for the pre-allocation of the data in a simple way by using limited lines of codes. Trus, have a look at the code given below:

Code:

p=zeros(5)

p(1,:)= [ 3 6 2 8 7]

for i=3:4

p(i,:)=p(i-1,:) +1

end

Output:

Understanding the MATLAB Code

In this code, we have used a simple function of zeros and used a loop to execute the whole instruction. Let us discuss both of them in detail:

Zeros Function

It is a pre-defined function of MATLAB that is used to make a null matrix of the required dimensions by using just a simple signal command. For the null matrices, there is the condition that the square matrix should be used.

For loop in Matrix

There are certain loops used in the MATLAB and with the help of this for loop, we just have to simply follow the syntax given below:


for index = value

statement

end

Here, the index value is the starting point where we want to start the matrix formation and the statement is the condition that we want to be executed while the formation of our matrix. If it is not clear right now in your mind, just have a look at the flow of the program.

  • First of all, we have used the zeros function to allocate the space in the memory according to the requirement. We have used the square matrix which has the order of 5 by 5. 

  • I wanted to pre-allocate the values in the matrix row after the row therefore, we simply changed the values of the matrix p formed before from 0 to other values defined by us. If you are not familiar with this function, have a look at the notation given below:

p(a,b)

Where,

a=number of row

b=number of column

As we did not want to alter any value in the columns so we have used a colon in its place. 

  • By using the for loops, we have specified that the index value starts from 3 and ends and 4. 

  • In the next step, we are using these index values and specifying to MATLAB that we want to change the values of the 3rd and 4th rows only and the program ends. 

  • MATLAB does this task step by step and changes the null or zero values of the matrix p into the required pre-allocated values in the matrix.

  • For the best concepts, we have changed the values of just two rows and the other matrix remains the same.

Larger versions of these kinds of procedures are used in diverse ways to recognize, store, and use the data in a better way, and with the help of this short program, we have seen a glimpse of a real-time application in which a matrix can be used to pre-allocate the different values and people can have benefit from it.

Trus, today, we have learned a lot about matrices and their applications. We have read great information about matrices in the past lectures and it was quite interesting to know how can you use these basic pieces of information in a better way and how people are working on the matrices to make their daily tasks easy during their professional life. We have seen different departments where matrices are making the work easy and more efficient. Most of them can not work without using matrices. Moreover, one must have the idea that many times we use matrices in our daily life unintentionally. As we have said earlier, 3D games require the involvement of a matrix. So, when your child is playing the game, he or she is enjoying the application of the matrices without knowing it. In the end, the small program was helpful to understand how little programs and the working of matrices are helpful to perform different tasks automatically.

Special Matrix Commands in MATLAB

Hello learners. Welcome to The Engineering Projects. We all know that matrices have been used in the engineering field for a long time, and they have a vital role in the calculation of different data. Therefore, we are learning about some very special kinds of matrices that are usually introduced to engineers at a higher level. Till now, we have seen some general operations on matrices and also examined the special kinds of matrices. Yet, today, we are moving a step forward and learning about some complex types of matrices that require strong basic concepts. So, have a glimpse at the topics that you are going to learn, and then, we’ll start practicing.

  • What is a matrix?

  • What are the different types of matrices that are less common?

  • How can we implement some interesting commands in MATLAB?

  • What is the procedure for dealing with complex equations in MATLAB?

What is a Matrix?

First of all, it is recommended to learn about the introduction of the matrix. A matrix has different elements in it with different sequences, and we define it as:

“A matrix is a rectangular array in which different types of elements in the different sequences are present, and all the elements are enclosed in a long bracket that is usually a square bracket.”

The sequence and the values of the matrices are important, and the collection of horizontal lines is called a row. On the other hand, the vertical entries are collectively called columns. To find the difference in the types of matrices, it is important to know that the basic kinds of matrices are square matrix and rectangular matrix. Most of the matrices that we are going to discuss here will be square matrices. 

Types of Matrices

Depending upon different parameters in matrices, these are divided into different types and groups. In a square matrix, the numbers of rows and columns are equal to each other, and in a rectangular matrix, the numbers of rows and columns are never equal. You will observe different parameters on the basis of which these matrices are recognized, and then the behavior of each of them is examined. So have a look at these types. 

A Boolean Matrix  

We all know that boolean numbers mean two conditions only, that are, zero and one. So, the boolean matrix is the type of matrix in which only zero and one value are used, and other values are never involved. The order of the matrix may be anything, but the entries must be either zero or one.

One thing that must be kept in mind is that the matrix will surely have these values in a non-specific pattern and it never has only zero or only one. There must be one and zero of each type. We are clearing it because some other types, such as singular matrix, identity matrix, null matrix, and scalar matrix, also involve zero and one, but in a specific manner. 

Boolean numbers and conditions are used in almost every field of mathematics, and therefore, this matrix is also used in different ways in such fields. With the help of a matrix, it becomes easy to deal with a large number of data points at once. The example we have shown here has a small size. Yet, when the boolean matrix is used in practical life, we use a bulk of matrices with greater sizes. 

Orthogonal Matrices

In the previous section, we learned that a transpose of the matrix is obtained when the rows and columns, along with the entries, are interchanged with each other. Keeping this concept in mind, we can define this type of matrix as

A matrix A is called an orthogonal matrix if and only if the multiplication of the matrix A with the transpose of itself provides us with the identity matrix. 

If you are new to the identity matrix, then you must know that an identity matrix is one that contains only value 1 in its diagonal and all the entries other than the diagonal are zero. 

The inverse of a Matrix

As we have read about the orthogonal matrices, they remind us of the inverse of the matrix. It is interesting to know that there exists the inverse of a matrix that, when multiplied with the original matrix, delivers us the identity matrix. We hope you remember that an identity matrix is a type of matrix that always has the value 1 in the diagonal elements and zero in all the remaining elements. So, if we are taking matrix A, then for the inverse matrix, we can say:

A.AT= I

In this way, if we have the value of A and want to know the inverse of it, we use the following equation:

AT= I/A

So, in this way, we have observed that no matter if the inverse of the matrix is multiplied with the original matrix or vice versa, we get the identity matrix. This condition is somehow special because the multiplication of the matrix is a more complex operation than addition and subtraction, yet here we are using the rules of the dot product. There is another way to find the inverse of a matrix with the help of a formula that states that the inverse of a matrix A is equal to the determinant of matrix A with an adjoint of A. 

There are certain conditions for the existence of a square matrix:

  • A matrix has the inverse only if it is a square matrix. 

  • If the determinant of the matrix is equal to zero, then there is no need to find the adjoint of that matrix because the inverse does not exist for that matrix. 

It is not always necessary that in the inverse of a matrix, the values are reciprocal of the original matrix. The values may also be changed, and by dot multiplication, we can get the identity matrix.

Stochastic Matrix

Here is another interesting type of matrix in which all the values show the probability values. We know that the probability values are so small that they are less than one and have fractional values or in the form of points less than one. So, the stochastic matrix has all the probability values as its elements.

You can see all the values are less than one because the probability is usually in the form of such small numbers. If any of the values is greater, then it is not a stochastic matrix. 

Nilpotent Matrix

This is a less common type of matrix in which Ak = O, that is, for every power of the matrix, we get a null matrix (the one with all the values equal to zero). There are two conditions that must be fulfilled in this type:

  1. The matrix A must be square.

  2. We get a null matrix every time we apply any power to matrix A, which is a natural number.

For example, when we take the square of each value of A, we get the null matrix. It is a less common type of matrix, but at a higher level of calculations, it has its applications. 

Idemportenet Matrix

It is a type of uncommon matrix that provides us with a matrix equal to itself when any power is applied to it greater than 2. That is, An = A where the value of n is always equal to or greater than 2. Usually, it has been noticed that if the square of the matrix A is equal to itself, then there is no need to check further because the result remains the same for any number greater than 2. You can take it as homework and find examples of such matrices by yourself.

Special Commands in MATLAB

It seems like you have learned a lot about the special kinds of matrices. When we talk about MATLAB, we have observed that there are different MATLAB commands that are not related directly to the matrices yet are used to make the functioning of a group of numbers and matrices easier and more effective in some cases. So, have a look at some of the commands.


sr#

Command

Description

1

inv(A)

This provides us with the inverse of the matrix A.

2

s,t, complex(s,t)

It is the way to introduce a complex number in MATLAB. It produces a complex equation with s as a real number and t as an imaginary number. 

3

real(A)

With the help of this command, you can find the real part of the equation saved as equation A.

4

imag(A)

By using this command, you can easily encounter the real part of the equation saved as equation A.

5

abs(A)

This command will show us the absolute value of the matrix A.

6

angle(A)

To find the angle of equation A, we use this command. 

The procedure to perform the Complex Number in MATLAB

We all know about complex numbers and have also used them in the matrices when we were talking about hermitian metrics. A special kind of function in MATLAB is the “complex” function, which is used to make the complex equation. So have a look at the step-by-step procedure to perform the complex equation in MATLAB.

  • Hit the start button of MATLAB. 

  • Go to the command window.

  • Start by writing the following command. 

a=3

w=3

  • It will provide us with two numbers that we will use in the complex function. We are naming this equation ComplexEqaution, and the command to perform this is

ComplexEqaution=complex(a,w)

  • Press the enter button. 

  • Now, using this equation, we can also find the real and imaginary parts of the equation using different commands. For real numbers, we are writing:

real(ComplexEqaution)

  • It will give us the real part of the equation. Similarly, write the following command for the imaginary number:

imag(ComplexEqaution)

  • Similarly, to obtain the absolute value of the equation we have just made, we are using the required command.

abs(ComplexEqaution)

  • Finally, to find the angle of the equation, we are using its command.

angle(ComplexEqaution) 

  • Now, to perform the inverse of a matrix, we are going to introduce the matrix first. So, write the following command:

B=[1 55 2 7; 4 5 2 8; 4 99 1 6; 3 8 4 1]

  • The command for this purpose is:

InversofMatrix= inv(B)

If you are confused about the absolute value of the complex equation, then you must realize that complex numbers are present in the plane or the coordinates of the system, and the absolute value of the complex numbers is defined as the total distance between the origin of the complex number (where the plane is (0,0)) and the complex plane (a,b). The procedure to do so is a little bit complex if we solve it theoretically, but with the help of MATLAB, this can be done with the help of a simple command and all the control in your hand. You should practice more with all these commands by using your own values in the matrix with a different sequence. Once you have followed all the instructions given above, the output at your MATLAB command window should be like the images given next:

So, in this way, we have gotten rid of the long and error-prone calculations, and by using simple commands, we have simply applied the formula of inverse, and in this way, we have not had to find the adjoint and determinant of the matrix A. 

Consequently, we had a little bit of a complex yet interesting lecture today on matrix, in which we defined it first for a solid foundation of the concept. After that, there were different types of matrices that are less common but have interesting patterns of the elements in which the values and positions are important to define the type of matrix. Moreover, we have seen some interesting commands in MATLAB to perform the operations of complex equations and also implement them all practically. In the next lecture, you are going to learn the amazing features and applications of MATLAB in different aspects of the study.

Special Types of Matrices in MATLAB

Hey students welcome to another tutorial in The Engineering Projects where we are going to learn a lot about matrices. If you are a beginner to the metrics, then you should go to learn the fundamentals of matrices. Yet, if you know the basic introduction, you are at the right lecture because we are learning about the special kinds of matrices and you are also going to see the matrices in action using MATLAB. So, here is a simple list of today’s topics. 

  • What is a matrix?

  • How can we identify the matrix with the help of its general form?

  • What are the different types of matrices?

  • What is the concept of transpose while dealing with matrices?

  • How can we implement these types of matrices in MATLAB by different commands?

What is a Matrix?

A matrix is a type of array that stores data of the same kind. It has great importance in the world of technology and it is defined as:

"A matrix takes the form of an ordered rectangular array surrounded by a square bracket and has entries of the same kind in the form of real or complex data."

To perform different operations on the matrices, you just have to apply them to the whole matrix at once; there is no need to apply them to all the entries one after the other. This will make sense when you see the matrices in action. 

Till now, we have learned about the basic introduction of the following types of matrices:

  • Row matrix

  • Column matric

  • Square matrix

  • Rectangular matrix

These are the basic types irrespective of the elements or entries present in them, and now, we are going to discuss some types that have the features of these matrices but the entries in them are in a specific pattern, so they are considered the special kinds of matrices. Before going into the details of each of them, there must be the foundation of a concept of a general form of the matrix. 

The General Form of the Matrix

To examine the location of a specific element, we use the terms "rows” and “columns” where

  1. Rows are the horizontal entries of the matrix.

  2. Columns are the vertical entries of the matrix.

A specific element is the part of a row and column at a time and to mention the location of an element, it is important to know the information about both of them. So, in the general form, a three-by-three matrix is shown as:

Where

  • A= name of the matrix
  • a= elements of the matrix A

Notice that a has two numbers with them in which the first number denotes the rows and the second one is the number of columns. To make it easier, we denote rows with i and columns with j. So we can say,

  • aij=a23=element of the second row and first column

Keeping this concept in mind, now it is easy to understand the types of matrices in which the value of the elements matters. Have a look at some of these types.

Identity Matrix

The identity matrix is a special kind of matrix having the arrangement of entries in such a way that all the diagonal entries are one and the remaining ones are all zero. In this way, we get the matrix of the form:

You can observe that for an identity matrix, the elements where i=j are all ones, and all the elements other than this are zero. There are certain applications of the identity matrix and you will know them in the upcoming lectures. 

Zero or Null Matrix

Here is an interesting type of matrix. This matrix has all the entries zero and no other value can be found in this element. So we assume the zero or null matrix as:

Where the sequence of the matrix can be any. No matter whether it square, row, or rectangular matrix. 

Singular Matrix

A singular matrix is the type of square matrix that has the determinant equal to zero. It is possible in the condition when all the entries of the matrix have the value one.

We all know the procedure to find the determinant. So, taking the determinant of this matrix C, we provide ourselves with the following calculations:

|C|=1x[(1x1) - (1x1)] - 1x [(1x1)-(1x1)] + 1x[(1x1)-(1x1)]

    =1x(1-1) - 1x(1-1) + 1x(1-1)

    =1x(0) - 1x(0) + 1x(0)

    = 0 - 0 + 0

    =0

So in general, we say, in a singular matrix:

|C| =0

Non-singular Matrix

A non-singular matrix, on the other hand, has entries in such a way that the determinant is never zero. So, we can say, most of the matrices are included in a non-singular type of matrix. Here is an example of a non-singular matrix, which we have also mentioned in other categories.

|C|=3x[(-6x7) - (1x-1)] - 0x [(2x7)-(1x4)] + (-5)x[(2x-1)-(-6x4)]

    =3x(-42+1) - 0x(14-4) - 5x(-2+24)

    =1x(-41) - 0x(-10) + 5x(22)

    = -41 - 0 + 110

    =69

Hence, we can conclude for the non-singular matrix that if A is a non-singular matrix, then:

|A|≠ 0

Diagonal Matrix

The concept of diagonal was used in the identity matrix, but it is a slightly different case. A diagonal matrix is one that has all the entries, other than the diagonal, equal to zero. The values in the diagonal may be anything. 

Here, one concept must be clear. In some cases, all the diagonal values except one may be zero, but it will still be called the diagonal matrix. In other words, by changing even one of the values in the null matrix, we can convert it into the diagonal matrix. 

Scalar Matrix

A scalar matrix has all the diagonal values the same, no matter what the value is, and all other values are zero. So, in the scaler matrix, three conditions must be satisfied:

  1. The values other than the diagonal are all zero. 

  2. The values in the diagonal must be non-zero.

  3. All the values of the diagonal are the same, no matter what the value is. 

  4. The matrix is a square matrix.

If one of the conditions is not satisfied, it is not a scalar matrix. 

Upper Triangular Matrix

This is an interesting type of matrix. The upper triangular matrix can be recognized when all the entries below the diagonals are zero and the entries above the diagonal are non-zero. So we get the matrix as:

The value in the diagonal must be non-zero for at least one value. And the 

The Lower Triangular Matrix

As you can guess, the lower triangular matrix has non-zero values in the lower elements than the diagonal. The values presented in the upper portion of the diagonal are all zero. So the lower triangular matrix looks like this:

Transpose of a Matrix

This is another concept in matrices that is important to discuss here because some types of matrices depend upon it. We know that a matrix has i rows and j columns. Then, the transpose of the matrix is defined as:

The transpose of matrix A, denoted by AT , is obtained when the rows and columns of matrix A are interchanged no matter what the total number of rows and columns. 

This concept is used in different ways, and the results obtained are important. To understand well, you must know, that a rectangular matrix of order 2 by 3 will be converted into a matrix of order 2 by 3 when the transpose is applied to it. 

Symmetrix Matrix

It is a special kind of matrix that involves the procedure of transpose. A skew-symmetric matrix is one that has the arrangement of elements in such a way that applying the transposed result in the matrix that has the same entries and same order. In other words:

AT=A

So, the skew-symmetric matrix is always a square.

The Skew Symmetrix Matrix

Here is another kind of square matrix that involves the transpose, and it is slightly different from the one discussed just before. This type of matrix, after taking the transpose, results in a matrix with all the negative values. So we define this in a simple way as

AT=-A

Harmatian Matrix

A hermitian matrix involves complex numbers in it. That means some, or all the elements of a matrix A are complex numbers, and the transpose of that matrix A results in the transpose of a conjugate matrix. So, the following conditions are applied to the hermitian matrix:

  • It is a square matrix.

  • It involves complex numbers.

  • A conjugate of the matrix is obtained. 

  • The resultant matrix has the conjugate values.

    The Skew Harmatian Matrix

    A skew hermitian matrix, with the complex conjugate, is the one that involves the negative values of the original matrix ( the one before the transpose procedure). It will be crystal clear to you when you examine the case given below:

    Special Matrices in MATLAB

    Are you enjoying the different types of matrices? Matrices are fun in MATLAB, it is good practice if we attempt all these types in MATLAB. Notice that, these types follow a specific sequence. Hence, MATLAB has a special function designed for the user with the help of which, one can have all these types by simply writing some commands. But it would be helpful if you understood the commands first.


    Command

    Description

    eye(a,b)

    It creates an identity matrix.

    Where

    a=number of rows

    b=numbers of columns


    triu(A)

    It converts the matrix A into the upper triangle.

    tril(A)

    It converts matrix A into the lower triangle.

    null(a,b)

    It creates a null matrix. 

    Where,

    a=number of rows

    b=numbers of columns

    ones(a,b)

    Creates the singular matrix having the rows a and columns b. 

    diag(A)

    Used to get only diagonals of the matrix provided by you as A.

    sort(A)

    Sort the elements of the matrix A in the ascending order column-wise.

    A’

    It takes the hermitian of a complex matrix A.


    Follow the procedure given below to perform the tasks.

    • Start your MATLAB software. 

    • Go to the command window.

    • Start typing the codes given below and get your desired matrix.

    A=[ 2 7 4; 5 11 5; 3 8 23]

    • Notice that we have a square matrix now. It will help us in different operations. So let’s start using different operations. 

    • Write your first command.

    IdentityMatrix=eye(3,3)

    • It will create an identity matrix with the name IdentityMatrix with three rows and columns.

    • Similarly, write the command given below:

     UpperTriangularMatrix=triu(A)

    • It's time to create the lower triangular matrix. So write the command.

     LowerTriangularMatrix=tril(A)

    • For the null matrix, we are going to use:

    NullMatrix=null(2,5)

    • For the singular matrix, we are using the following command:

    SingularMatrix=ones(3,4)

    • If you wish to have a diagonal matrix of A, write the command:

    DiagonalOfMatrix=diag(A)

    • To sort your matrix A, we are using the command given below:

    SortMatrix=sort(A)

    • If you want to find the hermitian of the matrix, first you have to introduce the complex matrix in MATLAB. So we are writing the following matrix:

    B = [1+j; 1-j; 2-j; 1+2j]    

    • Now, by simply applying the command, we can get the hermitian of this matrix.

    HermitianMatrix=B’

    Thus, today’s lecture was full of different types of matrices, and many of them were new to us. We began with the definition of the matrix, then we saw different types of it where the data or the elements of the matrix were important. Many of them have conditions where the order and location of the elements are important. The concept of transport in the matrix was new to us, and by using it, we explored different types. In the end, with the help of different commands in MATLAB and with the help of practice, we sharpened our concepts. There are different and interesting types of matrices, and we are going to explore all of them in our upcoming lectures.

    Basic Operations on Matrices in MATLAB

    Hey peeps, welcome to The Engineering Projects. We are talking about matrices, and if you want to learn them from scratch, you must go to the introduction to matrices in MATLAB. Today, we are learning how to perform different arithmetic operations on matrices. You will also see some interesting commands that are only applicable to the matrices. Here, it is important to notice that in MATLAB, the matrices are performed in the command window and there is no need to have the programming skills to perform them. Even if you are new to programming, you can easily perform the operations in MATLAB. We’ll discuss different basic operations on the matrices and will also perform each of them in MATLAB. Most of them are urinary operations and some of them are binary. Here is a small glimpse of today’s topics:

    • What is a matrix?

    • What are some basic operations of matrices?

    • What is an identity matrix?

    • How can we use the simple commands of MATLAB to perform complex and time-taking calculations with matrices?

    An Introduction to Matrices

    We all know what matrices are matrices. Yet, it is important to learn the basic definition of the matrices because this will create a map of how the basic operations on the matrices are performed. So, a matrix is defined as:

    “A matrix is a two-dimensional array with entries of the same kind in the form of real or complex data, and it takes the shape of an ordered rectangular array surrounded by a square bracket.”

    The thing to notice here is, that the data present in the matrices are of the same kind and therefore, we can perform a simple operation on each of the entries by simply applying it at once to the whole matrix.

    Now, have a look at the basic operations on the matrices. 

    Basic Operations on the Matrices

    There are several operations that can be performed on the matrices. Some of them are unary operations ( those operations that require only one matrix for the application) and most of them are binary operations that require two matrices for the performance. When you observe different types of each of them, we are going through the definition of each of them, and at the end, you will also practice each of them in MATLAB. So, have a look at the definition of each of them. 

    The Addition of the Matrices

    Yes, as you can guess, addition is a binary function, and you need two matrices to perform the addition of the matrices. The addition of the matrix takes place when both of the matrices have the same number of rows and columns. Each entry is added to the corresponding entry of the other matrix, and in this way, we get the resultant matrix with the same number of rows and columns. 

    One must keep in mind that addition is a commutative operation, which means if we have two matrices named A and B, respectively, then the addition process follows the rule given below:

    A+B=B+A

    All other rules are the same as the simple addition, but here, the equal number of rows and columns of the matrix is an additional rule that must be followed. 

    Subtraction of the Matrices

    As with the addition, the subtraction of the matrices is a binary operation, it requires the same order of both the matrices and does not follow the commutative rule. It means:

    A-B!=B-A

    And that makes sense. During the subtraction of B from A, the element on B at a particular location is subtracted from the element present on the corresponding entry of A. So, if the value of this particular element is less than the element subtracted from it, we get the answer in minus. Therefore, subtraction is not commutative.

    Multiplication of the Matrices

    The multiply operation in the matrices is somehow a little bit different from the normal multiplication. Two types of multiplication occur in the matrices:

    1. Multiplying the whole matrix with a scalar

    2. Multiplying two matrices 

    Multiplying a single number with the whole matrix is called scalar multiplication. If we are multiplying a number k with the matrix, the multiplication of k with the matrix provides us with a resultant matrix that has each entry having the value k times more than before multiplication.

    On the other hand, when two matrices are multiplied, the key point to remember is:

    During the multiplication of two matrices A and B, the number of rows of matrix A must be equal to the number of columns of matrix B; otherwise, the multiplication is impossible.

    Hence, if you are asked to multiply the matrices, this must be the first condition that you check. So, here is the procedure of matrix multiplication.

    • Check the number of rows and columns of matrices A and B.

    • Multiply each element of row 1 of matrix A with the column of matrix B. 

    • Add all the results of this multiplication together. 

    • Now, repeat the same procedure with the other rows of matrix A with the columns of matrix B.

    • In the end, you will get the resultant matrix that has the same number of rows as matrix A. 

    Therefore, the multiplication of the matrix is non-commutative and therefore we can say:

    AxB!=BxA

    This will be more clear when you learn the example in the next section. 

    Basic Operations on Matrix in MATLAB

    The solutions to the operations that we have mentioned above are time taking and require a number of steps to be followed. The same results, but in a better manner, can be obtained with the help of MATLAB. Just follow the steps to perform these operations in MATLAB. 

    Fire up your MATLAB software. 

    • Go to the command window.

    • Start writing the following code to make a matrix A in the command window:

    A=[ 2 5 8; 1 8 2; 4 6 9]

    • The resultant matrix will be shown on the screen. 

    • Now write the following code just below the matrix formed before:

    B=[1 5 2; 4 8 9; 2 7 3]

    The same result will be shown for matrix B. 

    • Now, to perform the addition of matrix A and B, write the following command in the command window:

    A+B

    It will show the results. 

    • Now write A-B. 

    You will get the results. 

    If you are performing all the operations according to the instructions, your screen will look like the following image:

    For the multiplication of both types, there are different commands. For the scalar multiplication, we are using the simple command given next:

    2*A

    It will provide us with a matrix that has two times the values of matrix A.

    For the multiplication of two matrices, the command A.*B is used. Here, the question arises why we are using the dot in between the A and B.  Have a look at the results of the different types of multiplication. We have mentioned the results when we used this command and a simple command of multiplication as A*B.

    Both types have different results. It is because using a dot between the A and B tells the compiler that we want the multiplication of each element with the other, and in this way, the authentic procedure for the multiplication is used as we have mentioned above in the multiplication section.

    Similarly, we are testing the same condition while we want the square of the matrix. We all know that a square means that each and every value is multiplied by itself. On the other hand, if we simply apply a formula to multiply value 2 with the whole matrix, we’ll get the double of each value but not the square. Let’s see this in action in MATLAB.

    You can clearly examine the difference between all the values. If we want to have the square of each element of matrix A, we have to use the third command with a dot between the matrices' names.

    Identity Matrix 

    In the discussion in the previous lecture, when we were talking about the types of matrices, we mentioned a type called the identity matrix. It is the matrix that has the arrangement of elements in such a way that only diagonal values are 1, and all the other values in the matrix are zero. It is an interesting type of matrix, and when talking about the procedure for having an identity matrix in MATLAB, it is more interesting. The following command is used to make an identity matrix:

    eye(x,y)

    Where,

    x=number of columns

    y=numbers of rows

    So basically, we are just telling the size of the matrix and MATLAB provides us with the result in a second, according to our wish. It may seem that it is a less common type of matrix, but that is not true. For many calculations, where the long and time-taking data is to be converted into a relatively simple identity matrix is used. It is also useful in systems where only binary data is used for calculations. There are some other uses of the identity matrix, but we are not going to discuss them because they are out of the scope of this lecture.

    Let’s see this in MATLAB:

    Interesting Commands Related to Matrix in MATLAB

    MATLAB provides us with great ease in dealing with the matrices and we can use them to easily get quick and easy access to our data. So go to the command window of your MATLAB again and run the following commands on it. It's fun. To compile all the things into just one table, we have added the commands that have been discussed in the early sections of this lecture.


    Command

    Description

    A=[1 3 6; 4 8 2; 6 11 3]

    It forms a matrix with the name A which has three rows and three columns with the same entries mentioned in the bracket.

    A(2,1)

    It provides us with the elements present in the second row and third column. 

    size(A)

    It shows us the size of matrix A, which is the number of rows and columns, respectively. 

    length(A)

    It is used to know the maximum number of rows or columns. It provides us with only one number, either of the rows or columns, which has the maximum value among two.

    A(:)

    It is the way to convert the whole matrix into a single column with all the entries one after the other in a vertical manner.

    A(:,2)=[ ]

    It is used to delete the 2nd column (or any other that is specified) and show the resultant matrix.

    A(1,:)=[ ]

    It deletes the first row and second column, then provides us with a matrix having the remaining entries.

    ones(2,4)

    It results in a matrix that contains two rows and four columns, but all the entries are one. 

    A’

    It is used to get the complement of the matrix A.

    These are some very basic commands that are related to the information that we have provided you till now. A great number of commands are also associated with the matrices in MATLAB, and we are going to discuss most of them in our discussion, but it is not possible to cover all of them in a single lecture. 

    Thus, today we learned a lot about matrices. We have observed some very basic but specific actions that are only possible when data is in the form of matrices. It was interesting to know that we could easily perform long calculations in MATLAB with the help of simple commands in no time. We have seen some interesting commands in MATLAB with detailed descriptions. We have also examined the output at each and every step. There are some other functions of MATLAB that help us get the results of complex commands in seconds. You must practice more by changing the elements or the numbers of rows and columns and check what results from you get with the same commands. In our next lecture, we have a lot of information about matrices.

    Introduction to Matrix in MATLAB

    Hello, learners welcome to The Engineering Projects. We are working on MATLAB, and in this tutorial, you are going to learn a lot about matrices in MATLAB. We are going to learn them from scratch, but we will avoid unnecessary details about the topic. So, without wasting time, have a look at the topics that you will learn in detail.

    • What is an array?

    • What is the matrix?

    • How can we declare a matrix in MATLAB?

    • What are the different types of matrices?

    • Can we find the unknown values of two equal matrices?

    • How can we solve the simultaneous equation in MATLAB?

    What is an Array?

    In this world of technology, the use of data is everywhere, and therefore, we can say there is a need for arrays in every field. You will find the reason soon. But before this, look at the introduction of an array.

     An array is a simple data structure that contains a collection of data presented in contiguous memory locations.

    So, the term “contiguous” used in the definition tells us that the data is in a continuous format, so we are not required to search here and there because the data is in a structured format. Moreover, arrays are of many kinds, such as

    • Two-dimensional arrays

    • Three-dimensional arrays

    In different types of cases, the suitable array is picked up so that we may get the best result with limited memory occupancy. With this type of foundation concept, we can now move forward toward our main topic, which is matrices. 

    What is a Matrix?

    In real-life applications and in higher studies, matrices are used in plenty in different forms, and therefore, we have decided to talk about them from a very basic level since it is important to understand the key features of the topics we are studying. Moreover, matrices are introduced in early classes, and it is important to refresh the basics in our minds so that we may proceed to the more complex problems. Here is the definition of "matrix":

    A matrix is a two-dimensional array in the form of an ordered rectangular array enclosed by a square bracket that has entries of the same kind in it in the form of real or complex data.

    The plural of the matrix is matrices, and sometimes the rectangular bracket is replaced by the parentheses according to the case. Just look at the image given below:

    This is a matric that contains nine elements, and you can also name this matric anything you want. In this way, it becomes easy to deal with more than one matrix, and you will see this action soon.

    Order of a Matrix

    To proceed forward, you must know the types of matrix and, for this, it is important to know the order of the matrix.

    The matrix given above is a square matrix and the horizontal lines are called columns, whereas the vertical entries are termed the rows of that particular matrix.

    If we represent the rows with the name m and the columns as n, then the order of the matrix is given as:

    mxn

    In this way, it is clear that the matrices given above have the order 3x4. If it seems to be an unnecessary thing to you, think again, because, with the help of order, we can know the type of a matrix and then perform different types of operations on it. But before this, have a look at some code in MATLAB to design matrices of different kinds. 

    Code for the Simple Matrix

    The Matrix is easily used in MATLAB, and you can start working with it by following the simple steps given below:

    • Start your MATLAB software.

    • Go to the command window.

    • Start writing the following code:

    A=[23 14 -8 33; 17 -102 0 37;3 -31 98 4];

    • Press enter. 

    In the image given overhead, these are the same entries that we have seen in the image given above, and in MATLAB, you will see the following result:

    The square bracket is not shown on the sides of the array in MATLAB. As you can see, the semicolon after every three entries indicates that the row is completed and the MATLAB compiler has to start the other row. 

    Here, A shows the name of the matrix that is compulsory, and you can name your matrix any word. If you do not follow the exact format and provide the number of entries different in rows, you will get the error. Once you know how to get started, you are ready to learn about the types of matrices.

    Types of Matrices

    There are several different types of matrices, and you can perform different arithmetic operations on the matrices only if they are of the same kind. This condition is not applied to all the operations, but most of them follow these rules. Here are some important types of matrices.

    Row Matrix

    A row matrix contains only one row and it is one of the simplest forms of a matrix. In this way, we get the matrix with a horizontal shape. The order of this matrix is:

    mxn=1xn

    Where n may be any number. 

    Column Matrix

    As you can guess, the column matrix is a type of matrix containing only one column and one or multiple rows. In this way, we get a matrix that has a vertical shape. Have a look at the order of a column matrix:

    mxn=mx1

    Where m may be any number, but the value of n is always one.

    Square Matrix

    A square matrix always has the number of rows and columns equal. It means, that no matter what the total number of entries is, the number of entries in each row and column must always be equal. In other words,

    m=n

    When you examine the example of a square matrix, you will get the reason why it is called so. The shape of this type of matrix is always square.

    Rectangular Matrix

    A rectangular matrix is one that has the arrangement of elements in such a way that the number of rows of the matrix is not equal to the number of columns. The same statement can be represented in the equation given next:

    m!=n

    Therefore, the matrix formed is in a rectangular shape, either in vertical format or horizontal format, according to the number of rows and columns.

    Diagonal Matrix

    We all know that the diagonal is the line or area that joins the upper left area with the lower right area of a rectangular or square. By the same token, a diagonal matrix is the one that contains all the diagonal values equal to zero and s in such a way that all the values other than the diagonal are zero. It will be clearer when you see the example of the diagonal matrix. We have set the examples of all the types of matrices that we have defined previously into a single MATLAB screen so you may have the best idea of each of them.

    Code and Output

    Moreover, here you can observe that instead of naming the matrices A, B, and so on, we have used the real names of the matrices for a clear declaration. Your homework is to make examples of each of them by yourself for the sake of practicing.

    Finding the Unknown Values Between Two Matrices

    Do you remember when we said the order of the matrix matters? This is one of the uses of an order of a matrix. Suppose we have two matrices named A and B, declaring that both are equal. This means that each corresponding value of a matrix A at position row 1 column 1 is equal to the corresponding value of the same position of matrix B. This is true for all the remaining values q of both matrices. Let me be clear with one example. Have a look at the picture given below:

    So, the value of r and, in return, the value of all r variables in each entry can be easily obtained by following the rules of the equation. It is one of the simplest examples of doing so, but in real life, we face complex problems. So, we use MATLAB for simplicity and accurate results. Have a look at the MATLAB code where we are going to show you an application of you can easily solve the simultaneous equation in MATLAB as well. 

    Solving Simultaneous Equations in MATLAB

    By using the property of the matrix of equality in more than one matrix, we can easily solve the simultaneous equations that are difficult and time taking if we solve them by hand. So let's see how we can declare and solve the simultaneous equation in MATLAB.

    Code:

    syms x y

    equa1= 6*x + 9*y==13;

    equa2= 9*x + 6*y==12;

    [A,B]= equationsToMatrix([equa1,equa2],[x,y])

    z=linsolve(A,B)

    Output:

    Understanding the Code

    To understand this code, you have to learn the basic definition of the function we have used in the code. It is the equationsToMatrix function. 

    equationsToMatrix Function

    The equationsToMatrix is a pre-defined function of MATLAB that converts the linear equation into a matrix so that we can use different operations on it more efficiently. It does it in the same way as we do in real life while solving the simultaneous equation with pen and paper. There are three types of syntax if this particular function. The one that we have used has the following syntax:

    [A,b] = equationsToMatrix(eqns,vars)

    Here, a minimum of two equations are required and the variables have the same condition. You must keep all the functions in mind and have to follow the exact syntax. Otherwise, it will show an error.

    linsolve Function in MATLAB

    In MATLAB, to solve the linear equation, we use this pre-defined function as it works in two ways:

    1. LU factorization with partial pivoting when in equation AB=X, A is a square. 

    2. QR factorization, otherwise.

    In our case, it has used the QR factorization. Now, you are able to understand the code clearly. 

    • First of all, the syms sign tells MATLAB that we are defining the variables. These may be one or more. But, we wanted two variables here, and we named them x and y. 

    • Now, we simply provide the values of the equation to MATLAB and store both of them into variables named equa1 and equa2 respectively. 

    • The values of variables and equations are fed into the eqautionToMatrix function to convert the linear simultaneous equation into a matrix for easy solving. 

    • In the end, we simply named a matrix z and told MATLAB that we wanted the value of variables x and y.

    Simultaneous Equation in MATLAB: Method 2

    By the same token, we can use the other method that is similar to it but the way it solves the equation is a little bit different. 

    Code:

    syms x y

    equa1= 6*x + 9*y==13;

    equa2= 9*x + 6*y==12;sol=solve([equa1,equa2],[x,y])

    asol=sol.x

     bsol=sol.y

    Output:

    Here, the only pone this is to understand. sol.x and sol.y are the functions that are used by the compiler to find the value of variables x and y respectively. You can use any variable with this sol function, after naming them at the beginning. After that, a variable is used to store and present the value of the answer obtained.

    It was an interesting lecture about the matrix, and we worked a lot from scratch to the end on many topics. We have defined the arrays and seen the introduction of the matrix. We also found information about the types of matrices. Once we have a grip on the basics, we learn that a matrix can be used to find the unknown value of two matrices, and as an application of this method, we found the values of the variable by using linear equations and learned how to declare, use, and solve the linear equation with the help of matrices in MATLAB.

    Introduction to the MATLAB Datatypes

    Hello friends. In this lecture, we are going to have a look at the different kinds of MATLAB data types.

    As we have already seen in previous lectures, MATLAB stands for MATrix LABoratory and allows us to store numbers in the form of matrices.

    Elements of a matrix are entered row-wise, and consecutive row elements can be separated by a space or a comma, while the rows themselves are separated by semicolons. The entire matrix is supposed to be inside square brackets.

    Note: round brackets are used for input of an argument to a function.

    A = [1,2,3; 4,5,6; 7,8,9];

    An individual element of a matrix can also be called using ‘indexing’ or ‘subscripting’. For example, A(1,2) refers to the element in the first row and second column.

    A larger matrix can also be cropped into a smaller matrix, as we can see in the example below.

    A scalar is just a special case of a matrix and its element size is 1x1. Square brackets are not needed to create a scalar variable. Also, a vector is a special case of a matrix with a single row or column. Square brackets without an element inside them create a null vector. We see examples of this in the code below:

    • u = [1 2 3]; %Produces a row vector
    • v = [1;2;3]; %Produces a column vector
    • X = []; %Produces a null vector

    Elements of a matrix can be all kinds of numeric datatypes, whether they are floating-point, integers, or imaginary numbers, as we will see in the next section. They can even be symbolic.

    DataTypes of MATLAB

    Every variable that is stored in the workspace of MATLAB has a datatype. It can be an in-built or default datatype or users can build their own datatypes depending on the purpose of the code.

    You can always find a datatype in MATLAB by using the 'class’ function.

    Numeric datatypes:

    Double:

    • This datatype takes 64 bits to store a number. This essentially represents a floating-point number, i.e., a decimal number with double precision, and can be positive or negative. You can use the function ‘double’ to declare the datatype when creating a variable, but double is the default datatype in MATLAB and whenever you call a command such as the one shown below, the number is stored as a double.
    • These variables can store values varying from between -1.79769 x 10308 and -2.22507 x 10-308 for the negative numbers and the range for positive numbers is between 2.22507 x 10-308 and 1.79769 x 10308 In situations where such large values of numbers are not needed, single-precision floating-point variable can be used.

    Single:

    1. When storing smaller numbers, it is better to use the single-precision floating-point numbers which vary between-3.4x10^38 and 3.4x10^38. This stores a variable in only 32 bits and helps to speed up the code. We use the function single in order to create this kind of variable.

    Integers:

    • MATLAB supports four types of signed integers and four types of unsigned integer datatypes, given by, int8, int16, int32, and in64 for the signed integers, and uint8, uint16, uint32 and uint64 for the unsigned integers. The number refers to the number of bits required to stored these integers and the range of allowed numbers is decided accordingly.

    Complex numbers:

    • You can create a complex number by using the ‘complex’ function or using the default symbol ‘i’ for the imaginary part of the complex variable. We can also extract the real and imaginary parts of the complex number using the ‘real’ and ‘imag’ functions on the complex number.

    Infinity and Nan:

    • Any number larger than the range given above is represented in MATLAB by the value ‘Inf’. Such a number can result when we divide by zero, which leads to results too large to represent as floating-point values and they end up being outside of the ranges discussed above. We can check if a variable is an infinity or not by using the function ‘isinf’ on it. Some numbers that can’t be represented by a real number such as the result of calculating ‘0/0’ or ‘inf/inf’ are called NaN, i.e., “Not a Number”. We can check if a variable is NaN or not by using the function ‘isnan’ on it.

    Logical:

    • These are variables that only have values of 0 and 1, and are the result of a comparison operation. An example of a result of comparing two matrices that gives a logical matrix as an output is shown below:

    Representation

    We can represent the output of a double in a shorter format which is easy to read or in a longer format which will help with learning about the accuracy of those double variables, using the commands below:
    • format short
    • format long

    Conversion of numeric datatypes:

    We can convert between double or single-precision numbers, as well as from floating-point to integers or vice versa using the functions described above which we use while declaring the numeric data type.

    Operations on numeric datatypes:

    Following is a list of operations on the numeric datatypes.

    • abs: to determine absolute and positive value of a signed or complex number.
    • Fix: round-off a floating point number towards 0. For example, fix([-2.1, 2.9]) = [-2, 2]
    • floor: round-off a floating point number towards –Inf. For example, floor([-2.1, 2.9]) = [-3, 2]
    • ceil: round-off a floating-point number towards +Inf. For example, ceil([-2.1, 2.9]) = [-2, 3] round: round-off a floating-point number towards the nearest integer. For example, round([-2.1, 2.9]) = [-2, 3]
    • Rem: Remainder after division of first argument by second argument. For example, rem(10,3)=1
    • Sign: signum function returns the sign of a number.

    Other datatypes:

    Characters/strings:

    • The character or string array is used to store text data in MATLAB.

    Single quotes are used to declare a character array. For example,

    A = ‘Hello World’ is a character vector.

    However, double quotes are used to declare a string. String is different from a character because individual parts of a character array can be accessed using indexing but the same is not true for strings.

    You can carry out the exercise shown below to understand this subtle difference.

    The various operations that can be performed on character array include:

    Cell matrix:

    • Just like matrices, a cell array is an indexed data container with each element known as a cell and can contain any type of data, including other cells and arrays which can be numeric or non-numeric types. Cells can be declared with curly braces, { } to let MATLAB know the input is a cell array. Individual cells inside a cell array can be called using round parentheses whereas contents at a location can be accessed by curly braces again, as shown in the example below:

    The function ‘cell2mat’ takes a cell as an argument and outputs a matrix. However, for this, all the elements of a cell array must be the same data type. This is what distinguishes Cell arrays from Matrices.

    Tables:

    • A table is a convenient data structure to write column-based or tabular datasets that can be stored in a text or spreadsheet file, or plotted easily as well. Tables let you access individual columns with variable names. Each variable can be a different datatype. The only restriction for different columns is for them to have the same number of rows. You can load the inbuilt tabular dataset inside MATLAB as shown below.

    Structures:

    • Structures are the most generic datatype in MATLAB which consist of indexed elements and each index can store a different datatype or in fact, a structure itself. Such structures are known as nested structures and the various branches of a nested structure can be accessed using the dot notation.

    Non-numeric datatypes also include function handles, symbolic variables and anonymous functions but they are a topic worth a separate lecture for discussion and will come up in the upcoming lectures.

    In further chapters, we will look at some of the applications of MATLAB in Linear algebra, look at different kinds of matrices inside MATLAB that are commonly used in a linear algebra class, and also work with input and output of data and functions using ‘m’ files as well as ‘mat’ files. We will also read about saving and loading operations, for input and output of data from MATLAB, and we will look further at making GUI in MATLAB, plotting linear, polar, 2D and 3D graphs with data sets.

    Introduction to MATLAB Command Window

    Hello friends! I hope you all had a great start to the new year.

    In our first lecture, we had looked at the MATLAB prompt and also learned how to enter a few basic commands that use math operations. This also allowed us to use the MATLAB prompt as an advanced calculator. Today we will look at the various MATLAB keywords, and a few more basic commands and MATLAB functions, that will help us keep the prompt window organized and help in mathematical calculations. We are also going to get familiar with MATLAB’s interface and the various windows. We will also write our first user-defined MATLAB functions.

    MATLAB keywords and functions

    Like any programming language, MATLAB has its own set of keywords that are the basic building blocks of MATLAB. These 20 building blocks can be called by simply typing ‘iskeyword’ in the MATLAB prompt.

    The list of 21 MATLAB keywords obtained as a result of running this command is as follows:

    • 'break'
    • 'case'
    • 'catch'
    • 'classdef'
    • 'continue'
    • 'else'
    • 'elseif'
    • 'end'
    • 'for'
    • 'function'
    • 'global'
    • 'if'
    • 'otherwise'
    • 'parfor'
    • 'persistent'
    • 'return'
    • 'spmd'
    • 'switch'
    • 'try'
    • 'while'

    To test if the word while is a MATLAB keyword, we run the command

    iskeyword(‘while’)

    The output ‘1’ is saying that the result is ‘True’, and therefore, ‘while’ is indeed a keyword.

    ‘logical’ in the output refers to the fact that this output is a datatype of the type ‘logical’. Other data types include ‘uint8’, ‘char’ and so on and we will study these in more detail in the next lecture.

    Apart from the basic arithmetic functions, MATLAB also supports relational operators, represented by symbols and the corresponding functions which look as follows:

    Here, we create a variable ‘a’ which stores the value 1. The various comparison operators inside MATLAB used here, will give an output ‘1’ or ‘0’ which will mean ‘True’ or ‘False’ with respect to a particular statement.

    Apart from these basic building blocks, MATLAB engineers have made available, a huge library of functions for various advanced purposes, that have been written using the basic MATLAB keywords only.

    We had seen previously that the double arrowed (‘>>’) MATLAB prompt is always willing to accept command inputs from the user. Notice the ‘’ to the left of the MATLAB prompt, with a downward facing arrow. Clicking this downward facing arrow allows us to access the various in-built MATLAB functions including the functions from the various installed toolboxes. You can access the entire list of in-built MATLAB functions, including the trigonometric functions or the exponents, logarithms, etc.

    Here are a few commands that we recommend you to try that make use of these functions:

    A = [1,2,3,4];

    B = sin(A);

    X = 1:0.1:10;

    Y = linspace(1,10,100);

    clc

    clear all

    quit

    Notice that while creating a matrix of numbers, we always use the square braces ‘[]’ as in the first line, whereas, the input to a function is always given with round brace ‘()’ as in the second line.

    We can also create an ordered matrix of numbers separated by a fixed difference by using the syntax start:increment:end, as in the third command.

    Alternatively, if we need to have exactly 100 equally separated numbers between a start and and end value, we can use the ‘linspace’ command.

    Finally, whatever results have been output by the MATLAB response in the command window can be erased by using the ‘clc’ command which stands for ‘clear console’, and all the previously stored MATLAB variables can be erased with the ‘clear all’ command.

    To exit MATLAB directly from the prompt, you can use the ‘quit’ command.

    In the next section, let us get ourselves familiarized with the MATLAB environment.

    The MATLAB Interface Environment

    A typical MATLAB work environment looks as follows. We will discuss the various windows in detail:

    When you open MATLAB on your desktop, the following top menu is visible. Clicking on ‘new’ allows us to enter the editor window and write our own programs.

    You can also run code section by section by using the ‘%%’ command. For beginners, I’d say that this feature is really really useful when you’re trying to optimize parameters.

    Menu Bar and the Tool Bar

    On the top, we have the menu bar and the toolbar. This is followed by the address of the current directory that the user is working in.

    By clicking on ‘New’ option, the user can choose to generate a new script, or a new live script, details of which we will see in the next section.

    Current Folder

    Under the Current Folder window, you will see all the files that exist in your current directory. If you select any particular file, you can also see it details in the bottom panel as shown below.

    Editor Window

    The Editor Window will appear when you open a MATLAB file with the extension ‘.m’ from the current folder by double clicking it, or when you select the ‘New Script’ option from the toolbar. You can even define variables like you do in your linear algebra class.

    The code in the editor can also be split into various sections using the ‘%%’ command. Remember that a single ‘%’ symbol is used to create a comment in the Editor Window.

    Workspace Window

    Remember that the semicolon ‘;’ serves to suppress the output. Whenever you create new variables, the workspace will start showing all these variables. As we can see, the variables named ‘a’, ‘b’, ‘c’, and ‘x’, ‘y’, ‘z’. For each variable, we have a particular size, and a type of variable, which is represented by the ‘Class’. Here, the ‘Class’ is double for simple numbers.

    You can directly right click and save any variable, directly from this workspace, and it will be saved in the ‘.mat’ format in the current folder.

    Live Editor Window

    If however, you open a ‘.mlx’ file from the current folder, or select the option to create a ‘New Live Script’ from the toolbar, the Live Editor window wil open instead.

    With the Live Script, you can get started with the symbolic manipulation, or write text into the MATLAB file as well. Live scripts can also do symbolic algebraic calculation in MATLAB.

    For example, in the figure below, we define symbol x with the command

    syms x

    We click ‘Run’ from the toolbar to execute this file.

    The Live Editor also allows us to toggle between the text and the code, right from the toolbar. After that, the various code sections can be run using the ‘Run’ option from the toolbar and the rendered output can be seen within the Live Editor.

    Command History

    Finally, there is the command history window, which will store all the previous commands that were entered on any previous date in your MATLAB environment.

    Figure window

    Whenever you generate a plot, the figure window will appear which is an interactive window with it’s own toolbar, to interact with the plots.

    We use the following commands to generate a plot, and you can try it too:

    X = 1:0.1:2*pi;

    Y = sin(X)

    plot(X,Y)

    The magnifier tools help us to zoom into and out of the plot while the ‘=’ tool helps us to find the x and y value of the plot at any particular point.

    Also notice that now, the size of the ‘X’ and ‘Y’ variables is different, because we actually generated a matrix instead of assigning a single number to the variable.

    Creating a New User-Defined Function

    By selecting New Function from the toolbar, you can also create a new user-defined function and save it as an m-file. The name of this m-file is supposed to be the same as the name of the function. The following template gets opened when you select the option to create a new user-defined function:

    The syntax function is used to make MATLAB know that what we are writing is a function filee. Again notice that the inputs to the function, inputArg1 and inputArg2, are inside the round braces. The multiple outputs are surrounded by square braces because these can be a matrix. We will create a sample function SumAndDiff using this template, that will output the sum and difference of any two numbers. The function file SumAndDiff.m looks as follows:

    Once this function is saved in the current folder, it can be recognized by a current MATLAB script or the MATLAB command window and used.

    Exercises:

    1. Create a list of numbers from 0 to 1024, with an increment of 2.
    2. Find the exponents of 2 from 0th to 1024th exponent using results of the previous exercise.
    3. What is the length of this matrix?
    4. Plot the output, and change the y axis scale from linear to log, using the following command after using the plot function: set(gca, ‘yscale’, ‘log’)
    5. Let us go ahead now and import an image into MATLAB to show you what the image looks like in the form of matrices. You need to have the image processing toolbox installed in order for the image functions to work.

    Run the following command in the MATLAB prompt:

    I = imread(‘ngc6543a.jpg’);

    This calls the image titled ‘ngc6543a.jpg’ which is stored inside MATLAB itself for example purposes. Notice the size of this image variable I in the workspace. You will interestingly find this to be a 3D matrix. Also note the class of this variable.

    In the next tutorial, we will deep dive into the MATLAB data types, the format of printing these data types and write our first loops inside MATLAB.

    Introduction to MATLAB

    Hello Friends! I hope you all are doing great welcoming 2022. With the start of the New Year, we would like to bring to you a new tutorial series. This tutorial series is on a programming language, plotting software, a data processing tool, a simulation software, a very advanced calculator and much more, all wrapped into one package called MATLAB.

    We would welcome all the scientists, engineers, hobbyists and students to this tutorial series. MATLAB is a great tool used by scientists and engineers for scientific computing and numerical simulations all over the world. It is also an academic software used by PhDs, Masters students and even advanced researchers.

    MATLAB (or "MATrix LABoratory") is a programming language and numerical computing environment built by Mathworks and it’s first version was released in 1984. To this day, we keep getting yearly updates. MATLAB allows matrix data manipulations, plotting of symbolic functions as well as data, implementation of robust algorithms in very short development time, creation of graphical user interfaces for software development, and interfacing with programs written in almost any other language.

    If you’re associated with a university, your university could provide you with a license.

    You can even online now! You can simply access it on…

    You can quickly access MATLAB at https://matlab.mathworks.com/ Here’s a small trick. You can sign up with any email and select the one month free trial to get quickly started with MATLAB online.

    And in case you can’t have a license, there’s also Octave, which is a different programming language but very similar in all the fundamental aspects to MATLAB. Especially for the purposes of these tutorials, Octave will help you get started quickly and you can access it on: https://octave-online.net/#

    Typical uses of MATLAB include:

    1. Math and numerical computation from the MATLAB prompt
    2. Developing algorithms and scripts using the MATLAB editor
    3. Modeling and simulation using Simulink, and toolboxes
    4. Data Visualisation and generating graphics
    5. Application development, with interactive Graphical User Interface
    6. Symbolic manipulation using MuPad

    MATLAB is an interpreted high-level language. This means any command input into the MATLAB interpreter is compiled line by line, and output is given. This is useful for using MATLAB as a calculator as we will see in the next section.

    Using MATLAB as an Advanced Calculator/ Beginner Commands

    By default, the MATLAB Prompt will be visible to you. The two angled brackets ‘>>’ refer to the MATLAB Command Prompt. Think of this as the most basic calculator. In fact, whenever you look at this, think of it as a Djinn asking for an input from you.

    Anything that you give it and press enter is known as a command. Whatever it outputs is known as the response. Whatever question you ask Matlab, it will be willing to respond quickly.

    For example, in the figure below, I simply write the command ‘2+2’ and press enter, to get the answer ‘4’ as a response.

    You can even define variables like you do in your algebraic geometry class.

    Notice that the semicolon ‘;’ that we see there is simply an indicator of when a statement ends like many other programming languages. Although this is not a necessary input in MATLAB, unlike many other languages which will simply give you an error if you forget this semicolon. Another function this serves is to suppress the output.

    In MATLAB, you don’t need to ask for the answer or the result to be printed and it will continue to print by itself as part of the response. However, if you don’t want to see the output, you can suppress it.

    You can also look at the value stored in a variable by simply writing the variable name and pressing ‘enter’.

    We can even create a matrix of numbers as shown in the image below. This can be a 1D matrix, or a 2D matrix. Notice the use of square brackets, commas and semicolons in order to create the matrix of numbers.

    You can even create matrices of numbers which are 3D numbers or even higher dimensions. When we will learn about images, we’ll see how an image is just a collection of numbers, and simple manipulation of those matrices will help us in manipulation of images.

    Saving Programs in MATLAB

    You can write and save your own commands in the form of an ‘m-file’, which goes by the extension ‘.m’. You can write programs in the ‘Editor window’ inside the MATLAB which can be accessed by selecting the ‘New Script’ button in the top panel. This window allows you to write, edit, create, save and access files from the current directory of MATLAB. You can, however, use any text editor to carry out these tasks. On most systems, MATLAB provides its own built-in editor. From within MATLAB, terminal commands can be typed at the MATLAB prompt following the exclamation character (!). The exclamation character prompts MATLAB to return the control temporarily to the local operating system, which executes the command following the character. After the editing is completed, the control is returned to MATLAB. For example, on UNIX systems, typing the following commands at the MATLAB prompt (and hitting the return key at the end) invokes the vi editor on the

    Emacs editor.

    !vi myprogram.m % or

    !emacs myprogram.m

    Note that the ‘%’ symbol is used for commenting in MATLAB. Any command that is preceded by this simple will be ignored by the interpreter and not be executed.

    In the figure above, we have saved our very first program titled ‘Program1.m’ using the editor window in MATLAB.

    Since MATLAB is for scientists and engineers primarily, it directly understands a lot of mathematical numbers natively, such as pi, e, j (imaginary number) etc.

    You can quickly go to the MATLAB or the Octave terminal to test this out. Just type pi, or e and press enter to see what you get.

    Introduction to Simulink

    MATLAB is also a great simulation software. For more sophisticated applications, MATLAB also offers SIMULINK which is an inbuilt simulation software and provides a block diagram environment for multidomain simulation and Model-Based Design. Simulink provides a graphical editor, customizable block libraries, and solvers for modelling and simulating dynamic systems.

    A very simple example of the Simulink block diagram model can be understood by the following model which simply adds or subtracts two or more numbers.

    The block diagram looks as follows:

    The model example for this can be opened using the following command.

    openExample('simulink/SumBlockReordersInputsExample')

    You can start playing with this model at once, on your MATLAB Desktop. And in fact you will find many more such examples of modelling and simulation programs that you can already start playing with online, in the set of MATLAB examples and also on the forum.

    The MATLAB Community and Forum

    MATLAB provides a whole community known as MATLAB-Central where MATLAB enthusiasts can ask questions and a lot of enthusiasts are willing to answer these forum questions.

    There is also also, ‘file-exchange’ which is part of MATLAB-Central where people post their programs, functions and simulations for anyone to use for free.

    MATLAB provides on-line help for all of its built­ in functions and programming language constructs. The commands lookfor, help, helpwin, and helpdesk provide on-line help directly from the MATLAB prompt.

    Introduction to MATLAB Toolboxes

    There are also several optional "toolboxes" available from the developers of MATLAB. These toolboxes are collections of functions written for special appli­cations such as symbolic computation, image processing, statistics, control system design, and neural networks. The list of toolboxes keeps growing with time. There are now more than 50 such toolboxes. The real benefit of using MATLAB is that there are teams of engineers and scientists from different fields working on each of these toolboxes and these will help you quickly get started into any field, after understanding the basics of the language. A lot of functions that are frequently performed in any particular research field, will be at the tips of your fingers in the form of ready-to-use functions. This will help you gain essential intuitions about all the different fields you may be interested in learning, getting started on, and quickly becoming a pro in. That’s the unique power MATLAB users wield.

    Over the coming tutorials, we will look at the wonders that can be performed with MATLAB.

    MATLAB can also interface with devices, whether they are GPIB, RS232, USB, or over a Wi-Fi, including your personal devices. It can help you manipulate images, sound and what not! You can also do 3d manipulation of animated models in MATLAB, and that’s very easy to do. We will go over this as well. We will also look one level below these 3d models and see how these themselves are also just numbers and coordinates in the end.

    I absolutely enjoy MATLAB, and there’s a simple reason I’m presenting this tutorial series to you. Because I believe you should enjoy it too!

    This will not only let you see ‘The Matrix’, which is the way computers perceive the real world around us, it will also change the way you yourself look at the world around you, and maybe you eventually start asking the holy question yourself… “Are we all living in a simulation?”

    Exercises

    Exercise: While you can get started on your own with the forum, and functions and simulations freely available, in order to procedurally be able to follow our tutorial and be able to build everything on your own from the scratch, we will strongly recommend you to follow our exercise modules.

    In today’s module, we will ask you to perform very basic arithmetic tasks that will give you an intuitive feel of how to use the MATLAB prompt as an advanced calculator and make the best use of it.

    For this we recommend finishing the following tasks:

    1. Use the following arithmetic operations to carry out complex calculations between any two numbers. The arithmetic operations are: Addition (+), subtraction (-), multiplication (*), division (/), and power(^).
    2. Also try to use basic math functions that are built-in for MATLAB such as, exp, log, sin, cos, tan, etc. Here are a few examples of commans you can run

    sin(pi/2) exp(4)

    log(10)/log(3)

    1. Also, define a few variables. Not only number variables, but also matrix variables as shown in the example below.

    a=1; b= 2; c = 3; A= [1,2,3,4]; B= [5,6,7,8];

    Notice that the case-sensitivity does matter for the name of the variables.

    Pro Tip: You can also perform the arithmetic operations of addition, subtraction, multiplication, division and power, element-wise between any two matrices. While addition and subtraction work element-wise by default, you can perform element-wise multiplication, division, and power by using the arithmetic operations as ‘.*’, ‘./’ and ‘.^’

    In the next tutorial, we will deep dive on the data types of MATLAB, keywords, what functions mean, and also write our very first function in MATLAB. If you are familiar with loops, that may come easy, because we will also write our very first loop that will help us perform repeated tasks with a relatively small number of commands.

    Calculating trigonometric Functions in MATLAB

    Hello everyone! I hope you all will be absolutely fine and having fun. Today, I am going to share my knowledge about Calculating Values of Trigonometric Functions in MATLAB. Trigonometric function have a great importance in latest mathematics. There are six types of trigonometric functions out of which first three are used more frequently in comparison to the other three. Trigonometric functions are important in the study of triangles. Trigonometric functions show the relationship between the angles of the triangle and the lengths of its sides. The positive and negative signs with the trigonometric functions indicate the portion of the quadrants. Well known theorem of mathematics i.e. Pythagoras Theorem is used in case of the right angle triangle and is totally based on the first three trigonometric functions.

    Calculating trigonometric Functions in MATLAB

    Here in the tutorial Calculating Values of trigonometric Functions in MATLAB, I will explain you that how can you calculate the values of trigonometric functions in MATLAB. First of all I would like to explain a bit about the trigonometric functions. They are important in the studies of triangles and depend upon some particular angle, as I have told earlier. There six types of trigonometric functions and they are given below.
    • sine
    • cosine
    • tangent
    • cosecant
    • secant
    • cotangent
    Suppose there is a particular angle ? then all of these functions can be written in MATLAB as shown below.
    • sin?
    • cos?
    • tan?
    • cosec?
    • sec?
    • cot?

     Calculating Values

    • Here I am going to calculate the values of the trigonometric functions in editor of the MATLAB.
    • First of all open the MATLAB software and open the editor then.
    • You need to define a time duration in which the function is defined.
    • Set the frequency of sinusoidal signal and write the function to calculate the value.
    • All of the above steps are shown in the figure below.
    • In the above figure you can see that I have define the duration from 0 to
    • I have adjusted the frequency of the signal as 5Hz.
    • And then I have written the desired function to calculate its value.
    • Since, I want to observe its value on the command window so I have removed the semicolon at the end of this statement as shown in the figure above.
    • The result displayed on the command window is shown in the figure below.
    • Similarly you can also calculate the values of all of the other trigonometric functions.
    • Here I am going to calculate the values of cosine and tangent functions for the same time duration and same frequency as well.
    • The code for calculating the values of the cosine and tangent functions is shown in the figure below.
    • You can see that there is no semicolon at the end of the last three statements because I want to observe the results of these three statements on the command window, if I put a semicolon, there will appear nothing on the command window then.
    • The results shown in the command window are shown in the figure below.
    • By scrolling up you can also observe the result of the sine function.
    So, that is all from the tutorial Calculating Values of trigonometric Functions in MATLAB. I hope you enjoyed this tutorial. If you face any sort of problem you can ask me in comments anytime without even feeling any kind of hesitation. I will try my level best to solve your issues in a better way, if possible. In my next tutorial I will explain you that how to Plot Simple Signal in MATLAB. I will explore MATLAB further in my later tutorials and will share all of them with all of you as well. So, till then, Take Care :)

    Generating Simple Signal in MATLAB

    Hello everyone! I hope you all will be absolutely fine and having fun. Today, I am going to share my knowledge about Generating Simple Signal in MATLAB. Signals are of great importance in our daily life. The signals are basically the graphical display of the analog values. We can estimate the severity level by the shape of the signals. The signals have a very wide range of applications in our daily lives. If we observe the shape of the AC voltages of 220V that is supplied in our homes, it is a sinusoidal signal. So, its an application of the signals. Signals also play a vital role in the medical field. While performing ECG and EEG tests in hospitals, doctors visualize the signals displayed on the screen and they can estimate the severity of the disease with the help of these signals. Depending upon the severity they suggest different medicines to the patients. Oscilloscope is a device to monitor the shape of the different signals usually present in engineering institutions. We can observe the shape of the voice, heat and a lot of other signals on it.

    Generating Simple Signal in MATLAB

    Here in the tutorial Generating Simple Signal in MATLAB, I will explain you the step by step procedure that how can you generate simple sinusoidal signal in MATLAB and how to visualize it.
    • First of all open your MATLAB software and open the editor.
    • Define a time duration at which the sinusoidal signal is completely defined.
    • Set the frequency of the sinusoidal signal.
    • Define the sinusoidal signal as the function of time and frequency.
    • Then at the end plot that sinusoidal signal across the time duration using the command
    • All of the above steps are shown in the figure below.
    • You can download the MATLAB simulation here by clicking on the button below.
    • Download .rar file, extract it and enjoy the complete simulation.
    • You can see that I have defined the time duration from 0 to
    • And adjusted the frequency of the signal as
    • Now press the Run button as encircled in the figure above.
    • A new figure having a sinusoidal signal will be appeared on the screen.
    • The sinusoidal signal is shown in the figure below.
    • Now, I am going to reduce the frequency of the signal to observe that what will happen to the shape of the signal.
    • I am going to reduce the frequency from 10 to 5Hz and want to observe the new shape of the signal.
    • The new code with the updated frequency is shown in the figure below.
    • The new signal generated is shown in the figure below.
    • If we compare the both of the signals we can conclude that there is an inverse relation between the frequency and the width of the signal.
    • Smaller the frequency greater will be the width of the signal and vice versa.
    • So, that was the brief description of the signal generation in MATLAB.
    So, that is all from the tutorial Generating Simple Signal in MATLAB. I hope you enjoyed this tutorial. If you face any sort of problem you can ask me in comments anytime without even feeling any kind of hesitation. I will try my level best to solve your issues in a better way, if possible. In my next tutorial I will explain you that how to Change the Properties of the Figure in MATLAB. I will explore MATLAB further in my later tutorials and will share all of them with all of you as well. So, till then, Take Care :)
    Syed Zain Nasir

    I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

    Share
    Published by
    Syed Zain Nasir