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 :)

Effect of Noise on 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 Affect of Noise on Signal in MATLAB. Noise is basically an unwanted signal that effects the normal signal. Noise the natural signal which can be removed but can be reduced to some extent. We can see a lot of examples of the signals effected by noise in our daily lives e.g. the distorted voice signal while calling, creates hearing problems, distorted TV signal makes the video invisible and the distorted AC signal can burn most of the home as well as other appliances. In signal processing term, noise is also known as the unwanted signal which carries no useful information. To recover the original signal from the noise effected one, is the basic and necessary goal of the signal processing. All of the filters including low pass, high pass, band pass, band reject (notch) are also designed for this purpose. Noise can never be removed completely but we can make its magnitude lower to some extent.

Effect of Noise on Shape of Signal

Here, in the tutorial Effect of Noise on Shape of Signal, I will elaborate that how noise an effect the shape and the information carried by the normal signal. Since noise is a random and unwanted signal having no useful information, so it has no fix shape, instead it could of any shape. Some of the shapes of the noise signals are shown below.
  • Noise across the time with random amplitude is shown in the figure below.
  • The noise signal displayed on the oscilloscope is 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.

Block Diagram
  • I have made a simple block diagram to explain the flow of the program.
  • The block diagram is shown in the figure below.
  • Noise is added in the signal and hence generated the noise effected signal.
Code Description
  • Just copy and paste the source code given below in your editor.
t=0:0.01:1;%time duration
x=sin(2*pi*5.*t);%orignal signal
noise = rand(1,101);%noise signal
corrupted_signal=x+noise;%noise effected signal
subplot(311);%division of figures
plot(t,x);%plotting
title('Orignal Signal');%title
subplot(312)%division of figures
plot(t,noise);%plotting
title('Noise Signal');%title of the corresponding signal
subplot(313)%division of figures
plot(t,corrupted_signal);%plotting
title('Corrupted signal');%title of the corresponding signal
  • First of all I have defined the time duration at which the signal is defined.
  • Then I have generated the original sinusoidal signal.
  • After that, I have generated a random noise.
  • Then the noise effected signal has been generated.
  • I have plotted all of the signals on the same figure but in different sections in order to visualize all of them.
  • As you run the program, a new figure having graphs will be appeared on the screen.
  • The figure containing graphs of all the signals is shown in the figure below.
  • That was the brief description of the source code for visualizing the Effect of Noise on Shape of Signal.
So, that is all from the tutorial Effect of Noise on Shape of Signal. I hope you enjoyed this tutorial. If you find any sort of problem, you can ask 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 elaborate that how to create a simple Graphical User Interface (GUI) in MATLAB and how to use it. I will further explore MATLAB in my later tutorials by making further projects on it and will share them with all of you as well. So, till then, Take Care :)

Convolution in MATLAB

Hello everyone! I hope you all will be absolutely fine and having fun. Today, I am going to share my knowledge about how to convolve the signals using an amazing software tool, MATLAB. MATLAB is an efficient tool for signal processing. MATLAB basically works on matrices. First of all I would like to tell you a bit about the convolution. In engineering terms, convolution describes the output of the Linear Time Invariant (LTI) systems.

Convolution is basically an integral which tells us about the overlapping of one function as it is shifted over another function. Convolution and cross correlation are similar. It has a wide range of applications e.g. computer vision, probability, statistics, engineering, differential equations, signal processing etc.

Convolution in MATLAB

Here in the tutorial, Convolution in MATLAB, I will tell you that how to convolve the two signals in MATLAB using built-in command, conv. Before going into the details of this tutorial, I would like to explain you about the convolution and its mathematical form.

  • You can download the MATLAB code or convolution of two signals here by clicking on the button below.
  • Download .rar file, extract it and enjoy the simulation.

In simple engineering terms, convolution is used to describe the out of the Linear Time Invariant (LTI) systems (the systems which shows different response at different times). Convolution is similar to cross correlation. Input output behavior of the system can be estimated with the help of the impulse response of that system. And the output of the system can be obtained by convolving the input applied to the system and impulse response of that system.

  • Suppose x(t) is the input applied to the system and h(t) is the impulse response of the system.
  • Its output y(t) can be obtained using the mathematical expression given below.

y(t) = x(t)*h(t)

  • In above expression * sign expresses the convolution between the input and the impulse response of the system.
Block Diagram
  •  I have made a very simple block diagram representation of convolution.
  • The input x(t) is applied to the system.
  • The system has convolved the input x(t) and the impulse response of the system h(t) to obtain its output y(t).
  • The block diagram is shown in the figure below.
Signal Representation
  • The convolution can also be represented in the form of signals.
  • The figure shown below displays the convolution between input and impulse response of the system in order to obtain its output.
Source Code Description
  • Just copy and paste the source code give below in your MATLAB editor to observe the convolution results.
clc %clears the command window
clear all %clears the workspace
t1 = 0:1:1;%time duration for the first signal
t2 = 0:2:10;%time duration for the second signal
f1 = 3;%frequency of the first signal
f2 = 5;%frequency of the first signal
x = sin(2*pi*f1.*t1);%first signal
y = cos(2*pi*f2.*t2);%second signal
convolution = conv(x,y) %convolution of both the signals x & y
  • You can see first of all I have cleared the command window and the workspace.
  • Then I have declared time duration for both the signals.
  • After that I have defined the frequency for the both signals.
  • Then I have defined the two different sinusoidal signals.
  • At the end I have convolved both of them and removed the semicolon at the end of the statement in order to observe the results on command window in MATLAB.
  • So, that was the brief description of the code, you can download it from the above button.
  • The result shown on the command window are shown in the figure below.
  • That was the brief discussion about how to convolve two signals in MATLAB using builtin commands conv.

So, that is all from the tutorial Convolution in MATLAB. I hope you enjoyed this tutorial. If you find any sort of problem, you can ask 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 elaborate that how to declare the variables in MATLAB and how to manipulate them without assigning them with the values. I will further explore MATLAB in my later tutorials. So, till then, Take Care :)

ECG Digitization in MATLAB

Buy This Project Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to do ECG Digitization in MATLAB. If you are new to ECG signals then you should have a look at Introduction to ECG. I have also posted many different simulations on ECG in which I have extracted different features of ECG signals but in today's tutorial, we are gonna extract the ECG signal itself from its image. I have also saved this ECG signal in a txt file so that you can use it. This code is not open source and you can buy it from our shop by clicking the above button. I have designed a GUI in MATLAB and it will take image of ECG signal as an input and then will give the digital form of that ECG signal as an output. There are few restrictions on this code and its not necessary that it will work on all images of ECG signal, but I am sure it will work on most of them. I have also added three images in the folder which works great with this code. You should also have a look at ECG Simulation using MATLAB and ECG Averaging in MATLAB. So, let's get started with ECG Digitization in MATLAB:

ECG Digitization in MATLAB

  • When you will buy this MATLAB code, you will get an rar file.
  • Extract this rar file and it will contain below files in it:
  • You need to run Main.m file which is a MATLAB file.
  • Open this file in MATLAB and run it.
  • If everything goes fine then it will open up as shown in below figure:
  • Click this button which says Load Image File.
  • When you click this button, it will open up a dialog box as shown in below figure:
  • Here you need to select the image of ECG signal, which you want to digitize.
  • So, I am selecting ECG1.png and the results are shown in below figure:
  • The first axes is showing the ECG Image file as it is.
  • I have converted this ECG Image File into Gray Scale which is shown in axes 2.
  • Further, I have converted this Dray Scale Image into Binary Image which is shown in axes 3.
  • If you have noticed we have a blue line in ECG Binary Image.
  • I have added this line and taken it as an x-axis, the algo is reading the values of black pixels and then subtracting it from this x axis line.
  • In this way, I am getting my complete ECG Signal and the Axes 4, which is named as ECG Signal, is displaying this digital ECG Signal.
  • I have converted pixels into mV, which you can change by yourself in the code.
So, that was all about ECG Digitization in MATLAB. If you got into any trouble regarding this project then you can ask in comments and I will try my best to resolve them. Thanks for reading !!! :)

ECG Averaging in MATLAB

Buy This Project Hello friends, I hope you are doing great. Today, I am going to share an expert level project which is ECG Averaging in MATLAB. If you are new to ECG then you should have a look at Introduction to ECG. I have already shared ECG Simulation using MATLAB in which we have seen how to simulate an ECG signal and then diagnose heart disease. We have also extracted ECG features in that project. So, if you guys haven't read that tutorial then I would suggest you to not read this one. First read ECG Simulation using MATLAB and then you should read this tutorial. Today's project is quite an extension of our previous project ECG Simulation using MATLAB. Our team has designed this project after quite a lot of effort that's why its not free to use but you can easily buy it from our shop using PayPal, by clicking the above button. In today's tutorial, we are gonna have a look at How to do ECG Averaging in MATLAB. ECG Signals normally have a lot of noise in them that's why its quite necessary sometimes to average the ECG signal so that we get better results. That's where ECG averaging is required. So, lets get started with ECG Averaging in MATLAB.

ECG Averaging in MATLAB

  • Let me first explain in detail why we need to average an ECG signal and how we are gonna do that.
  • Check ECG signal shown in below figure:
  • In the above ECG signal, we can see there's a lot of noise in ECG waveform, which may affect our results so there's a need to apply some filters to smoothen out the ECG waveform.
  • Another way of removing noise is ECG averaging.
  • In ECG averaging technique, we cut signle ECG signal and then we extract all of our peaks.
  • Finally we add them up and create an average waveform.
  • I have shown this whole procedure in below figure:
 
  • In the above figure, you pretty much got the idea behind this project.
  • Now here's its MATLAB GUI, shown in below figure:
  • It has two Containers at top and a full length Graph at the bottom.
  • Now, when you Click the Button the it will ask for the ECG data file, as shown in below figure.
  • Currently this project has eight data files with it and I have tested all of them and they are working quite fine.
  • I have downloaded all the data files from Phsio Bank website. You can read its more details in ECG Simulation using MATLAB.
  • Now when you will upload the files then it will take all the peaks and then will add them up one by one and will give you final output in the right container.
  • The whole procedure for data1 is shown in below figure:
  • I hope now you got the complete idea of its working but still if you have any questions then you can ask in comments and I will help you out.
  • Here's the final look of this project:
  • I have also created this video in which I have explained it in more detail and shown how it works.
  • So, if you wanna buy this Project then I would suggest you to must watch this video before so that you got the complete idea of what you are buying.
  • Here's the video for ECG Averaging in MATLAB:
So, that's all for today. I hope you have enjoyed today's tutorial. Will see you guys in next tutorial. Till then take care and have fun !!! :)

MATLAB Image Processing

Hello everyone! I hope you all will be absolutely fine and having fun. Today, I am going combine all of my previously published tutorials based on MATLAB Image Processing. Image processing can be defined as to convert an image into digital form and to perform some actions on it to improve its quality. I have published a number of tutorials on MATLAB image processing but they are not well arranged. So, I am going to combine the links for all of them in order to access them easily. All of the projects that I am going to combine today, are designed and compiled by our team with a lot of hard work. A number of MATLAB Image Processing based tutorials are compiled into this single tutorial. These are divided into two different categories i.e free and payable. Some of them are totally free and their source code are easily available to download. Some are not free but we have imposed a low cost on it and the students can easily purchase them even with their pocket money as well. Image processing is an amazing technique now a days and is difficult to do that is why we have imposed a bit cost on some of the major projects. The detailed description of each of the single project based on MATLAB image processing will be given later in this tutorial.

MATLAB Image Processing

Here in the tutorial MATLAB Image Processing, the combined list of all the previously published tutorials will be given in detail along with their accessible links. First of all I would like to explain you a bit about image processing technique.
  • To convert an image into the digitized form and perform some kind of actions on it specially to improve its quality is basically known as image processing technique.
  • The images below display the conversion of an image into digitized form to improve their quality.
  • The image on which I am going to perform some of the actions for its quality improvement is shown in the figure below.
  • Now I am going to perform some of the major actions on it to improve its quality.
  • The figure shown below displays the tasks performed on the above image.
  • So that was a bit about image processing technique.
  • Now, I am going to combine all of my previous tutorials based on MATLAB image processing.

1) Color Detection in Images using MATLAB

This tutorial is about the detection of a specific color among different colors on an image using an amazing tool i.e MATLAB. Color detection becomes necessary sometimes. Like there different cars with same external structure and same specifications but they have different colors. We have to select a red colored car using computerized automated system, to wash it. Here we need to apply an image processing technique to detect the red color among all of the different colors present at a time. In this tutorial I have take an image having red, green and blue colors in it. I have individually detected each of the colors from this image using MATLAB image processing technique.
  • You download the complete simulation here by clicking on the button below.

Download Color Detection in MATLAB using Image Processing

2) Detect Circles in Images using MATLAB

In this tutorial I have explained the methods for the detection of the circles in MATLAB. Its a quite simple technique. The first thing is to choose an image on which the circles are to be detected. Then the second step is the detection of the circles on the selected image. I have used an image of bicycle having two circles i.e. its wheels as shown in the figure on right side. You can see there are two circles in the image. MATLAB finds the circles first and then shows them to us by detecting them. For this figure MATLAB has found both of the wheels and shown us the detected wheels as white and red dotted line on inner surface of both of the wheels of bicycle.
  • You download the complete MATLAB simulation here by clicking on the button below.

Download Detect Circles in Images using MATLAB

3) Image Zooming with Bilinear Interpolation

In this tutorial I have elaborated the technique for the image zooming with bilinear interpolation in MATLAB. Different software e.g. paint and adobe photoshop provides us with the option of zooming the image bu just clicking on the button. In this tutorial I have performed the operation of image zooming in MATLAB using bilinear interpolation. In MATLAB, zooming of an image means that we are increasing the pixels of that image. In order to do so we must have to fill the extra pixels with color of the neighbor pixels. To fill out the extra pixels with some color is usually known as the interpolation. There are a lot of interpolation techniques. I have used a type of linear interpolation named as bilinear interpolation which includes the implementation of interpolation formula on both x and y axis. You can see the further details i.e. interpolation formula and its implementation, for this project by clicking on the button below.
  • You can download the complete MATLAB simulation for image zooming with bilinear interpolation, just here by clicking on the button below.

Download Image Zooming with Bilinear Interpolation

4) Color Detection in MATLAB Live Video

In this tutorial I have made an algorithm for color detection in MATLAB live video. I have taken a live video from my laptop's camera and then I have detected the specific color from the live video. In order to do this task, you must have to install image processing toolbox in your MATLAB. I have detected a red color in this tutorial. You can detect any color you want. You have to made a very small change in the code in order to do so. For this tutorial, you can place anything having red color in it, in front of the camera. Algorithm will detect and encircle the red color in that image. The algorithm in working condition is also shown in the figure on right side.
  • You can download the complete MATLAB simulation for color detection in MATLAB live video, here by just clicking on the button below.

Download Color Detection in MATLAB Live Video

5) Motion Detection in MATLAB

In this tutorial, I have made an algorithm for the detection of the motion in MATLAB. This project can be used as the security purposes. For hardware purpose IR sensor is used to detect the motion in the surroundings. I have used MATLAB software for the motion detection in the real environment instead. I have used a webcam and then applied a simple algorithm in order to detect the motion in the surroundings. I have made GUI having different sections on it. on the first axis the image is to be captured and then you need to press Start Comparison button to visualize the change in surroundings. If any change is occurred in the environment or not, corresponding text will be displayed on the GUI at the bottom right corner of the GUI.
  • You can download the complete MATLAB simulation for Motion Detection in MATLAB, here by just clicking on the button below.

Download Motion Detection in MATLAB

6) Eye Ball Detection in MATLAB

In this project I have designed an algorithm for Eye Ball Detection in MATLAB. I have designed a Graphical User Interface (GUI) to detect the eye balls from the images loaded into the GUI. Our team has worked very hard to design this algorithm. So, I have not share the simulation for this task for free. I have imposed a small amount of cost on it. You can easily buy this project by clicking on the button below. The algorithm is designed in MATLAB 2015 version. So, you must have MATLAB 2015 or its later version because it is not backward compatible. As you run the simulation a GUI will be opened on your screen. You just need to browse the image in which eye balls are needed to be detected. Then press the Load button, you will see that eye balls has been detected successfully as shown in the figure on right side.
  • You can download the complete MATLAB simulation for Eye Ball Detection in MATLAB, here by just clicking on the button below.

Buy Eye Ball Detection in MATLAB

So, that is all from the tutorial MATLAB Image Processing. I hope you all enjoyed this tutorial.If you face any sort of problem, you can ask me freely anytime in comments without even feeling any kind of hesitation. I will try my level best to entertain you and to sort out your issues in some better way, if possible. I will explore this technique further in MATLAB and on the other software as well in my later tutorials. 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