Social Distancing Detector with OpenCV in Raspberry Pi 4

During the era of Covid-19, social distancing has proven to be an efficient method of reducing the spread of contagious viruses. It is recommended that people avoid close contact as much as possible because of the potential for disease transmission. Many public spaces, including workplaces, banks, bus terminals, train stations, etc., struggle with the issue of keeping a safe distance.

The previous guide covered the steps necessary to connect the PCF8591 ADC/DAC Analog Digital Converter Module to a Raspberry Pi 4. On our Terminal, we saw the results displayed as integers. We dug deeper into the topic, figuring out exactly how the ADC produces its output signals. In this article, however, we will use OpenCV and a Raspberry Pi to create a system that can detect when people are trying to avoid eye contact with one another. We will employ the YOLO version 3 Object Recognition Algorithm's weights to implement the Deep Neural Networks component. Compared to other controllers, the Raspberry Pi always comes out as the best option for image processing tasks. Previous efforts utilizing Raspberry Pi for advanced image processing included a face recognition application.


Where To Buy?
No.ComponentsDistributorLink To Buy
1Jumper WiresAmazonBuy Now
2PCF8591AmazonBuy Now
3Raspberry Pi 4AmazonBuy Now

Components 

  • Raspberry Pi 4

Only a Raspberry pi 4 having OpenCV pre-installed will do for this purpose. Digital image processing is handled with OpenCV. Digital Image Processing is often used for people counting, facial identification, and detecting objects in images.

YOLO

The savvy YOLO (You Only Look Once) Convolution neural networks (CNN) in real-time Object Detection are invaluable. The most recent version of YOLO, YOLOv3, is a fast and accurate object identification algorithm that can identify eighty distinct types of objects in both still and moving media. The algorithm first runs a unique neural net over the entire image before breaking it up into areas and computing border boxes and probability for each. The YOLO base model has a 45 fps real-time frame rate for processing photos. Compared to other detection approaches, such as SSD and R-CNN, the YOLO model is superior.

In the past, computers relied on input devices like keyboards and mice; today, they can also analyze data from visual sources like photos and videos. Computer Vision is a computer's (or a machine's) capacity to read and interpret graphic data. Computing vision has advanced to the point that it can now evaluate the nature of people and objects and even read their emotions. This is feasible because of deep learning and artificial intelligence, which allow an algorithm to learn from examples like recognizing relevant features in an unlabeled image. The technology has matured to the point where it can be employed in critical infrastructure protection, hotel management, and online banking payment portals.

OpenCV is the most widely used computer vision library. It is a free and open-source Intel cross-platform library that may be used with any OS, including Windows, Mac OS X, and Linux. This will make it possible for OpenCV to function on a mobile device like a Pi, which will have a wide range of applications. Let's dive in, then.

Setup of OpenCV on a Raspberry Pi 4

OpenCV and its prerequisites won't run without updating the Raspberry Pi to the latest version. To install the most recent software for your Raspberry Pi, type in the following commands:

sudo apt-get update

Then, use the scripts below to set up the prerequisites on your RPi so you can install OpenCV.

sudo apt-get install libhdf5-dev -y 

sudo apt-get install libhdf5-serial-dev –y 

sudo apt-get install libatlas-base-dev –y 

sudo apt-get install libjasper-dev -y 

sudo apt-get install libqtgui4 –y

sudo apt-get install libqt4-test –y

Finally, run the following lines to install OpenCV on your Raspberry Pi.

pip3 install OpenCV-contrib-python==4.1.0.25

Setting up Opencv using Cmake

OpenCV's installation on a Raspberry Pi can be nerve-wracking because it takes a long time, and there's a good possibility you'll make a mistake. Given my own experiences with this, I've tried to make this lesson as straightforward and helpful as possible so that you won't have to go through the same things I did. Even though OpenCV 4.0.1 had been out for three months when I started writing this lesson, I decided to use the older version (4.0.0) because of some issues with compiling the newer version.

This approach involves retrieving OpenCV's source package and compiling it on a Raspberry Pi with the help of CMake. Installing OpenCV in a virtual environment allows users to run many versions of Python and OpenCV on the same computer. But I'm not going to do that since I'd rather keep this essay brief and because I don't anticipate that it will be required any time soon.

Step 1: Before we get started, let's ensure that our system is up to date by executing the command below:

sudo apt-get update && sudo apt-get upgrade

If there are updated packages, they should be downloaded and installed automatically. There is a 15-20 minute wait time for the process to complete.

Step 2: We must now update the apt-get package to download CMake.

sudo apt-get update

Step 3: When we've finished updating apt-get, we can use the following command to retrieve the CMake package and put it in place on our machine.

sudo apt-get install build-essential cmake unzip pkg-config

When installing CMake, your screen should look similar to the one below.

Step 4: Then, use the following command to set up Python 3's development headers:

sudo apt-get install python3-dev

Since it was pre-installed on mine, the screen looks like this.

Step 5: The following action would be to obtain the OpenCV archive from GitHub. Here's the command you may use to replicate the effect:

wget -O opencv.zip https://github.com/opencv/opencv/archive/4.0.0.zip

You can see that we are collecting version 4.0.0 right now.

Step 6: The OpenCV contrib contains various python pre-built packages that will make our development efforts more efficient. Therefore, let's also download that with the command that is identical to the one shown below.

wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.0.0.zip

The "OpenCV-4.0.0" and "OpenCV-contrib-4.0.0" zip files should now be in your home directory. If you need to know for sure, you may always go ahead and check it out.

Step 7: Let's extract OpenCV-4.0.0 from its.zip archive with the following command.

unzip opencv.zip

Step 8: Extraction of OpenCV contrib-4.0.0 via the command line is identical.

unzip opencv_contrib.zip

Step 9: OpenCV cannot function without NumPy. Follow the command below to begin the installation.

pip install numpy

Step 10: In our new setup, the home directory would now contain two folders: OpenCV-4.0.0 and OpenCV contrib-4.0.0. Next, we'll make a new directory inside OpenCV-4.0.0 named "build" to perform the actual compilation of the Opencv library. The steps needed to achieve the same result are detailed below.

cd~/opencv

mkdir build

cd build

Step 11: OpenCV's CMake process must now be initiated. In this section, we specify the requirements for compiling OpenCV. Verify that "/OpenCV-4.0.0/build" is in your path. Then, paste the lines below into the Terminal.

cmake -D CMAKE_BUILD_TYPE=RELEASE \

    -D CMAKE_INSTALL_PREFIX=/usr/local \

    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.0.0/modules \

    -D ENABLE_NEON=ON \

    -D ENABLE_VFPV3=ON \

    -D BUILD_TESTS=OFF \

    -D WITH_TBB=OFF \

    -D INSTALL_PYTHON_EXAMPLES=OFF \

    -D BUILD_EXAMPLES=OFF ..

Hopefully, the configuration will proceed without a hitch, and you'll see "Configuring done" and "Generating done" in the output.

If you encounter an issue during this procedure, check to see if the correct path was entered and if the "OpenCV-4.0.0" and "OpenCV contrib-4.0.0" directories exist in the root directory path.

Step 12: This is the most comprehensive process that needs to be completed. Using the following command, you can compile OpenCV, but only if you are in the "/OpenCV-4.0.0/build" directory.

Make –j4

Using this method, you may initiate the OpenCV compilation process and view the status in percentage terms as it unfolds. After three to four hours, you will see a completed build screen.

The command "make -j4" utilizes all four processor cores when compiling OpenCV. Some people may feel impatient waiting for a 99% success rate, but eventually, it will be worth it.

After waiting an hour, I had to cancel the process and rebuild it with "make -j1," which did the trick. It is advisable first to use make j4 since that will utilize all four of pi's cores, and then use make j1, as make j4 will complete most of the compilation.

Step 13: If you are at this point, congratulations. You have made it through the entire procedure with flying colors. The final action is to run the following command to install libopecv.

sudo apt-get install libopencv-dev python-OpenCV

Step 14: Finally, a little python script can be run to verify that the library was successfully installed. Try "import cv2" in Python, as demonstrated below. You shouldn't get any error message when you do this.

Completing the Raspberry Pi Software Installation of Necessary Additional Packages

Let's get the necessary packages set up on the Raspberry Pi before we begin writing the code for the social distance detector.

Installing imutils

utils are designed to simplify the use of OpenCV for standard image processing tasks like translating, rotating, resizing, skeletonizing, and presenting pictures via Matplotlib. If you want to get the imutils, type in the following command:

pip3 install imutils

A Breakdown of the Program

The complete code may be found at the bottom of the page. In this section, we'll walk you through the most crucial parts of the code so you can understand it better. All the necessary libraries for this project should be imported at the beginning of the code.

import numpy as np

import cv2

import imutils

import os

import time

Distances between objects or points in a video frame can be determined with the Check() function. The two things in the picture are represented by the a and b points. The Euclidean distance is determined using these two positions as the starting and ending points.

def Check(a,  b):

    dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5

    calibration = (a[1] + b[1]) / 2     

    if 0 < dist < 0.25 * calibration:

        return True

    else:

        return False

The YOLO weights, configuration file, and COCO names file all have specific locations that can be set in the setup function. The os.path module is everything you need to do ordinary things with pathnames. The os.path.join() sub-module intelligently combines two or more path components. cv2.dnn.read The net is reloaded with the saved weights using the netfromdarknet() function. Once the weights have been loaded, the network layers can be extracted using the getLayerNames model.

def Setup(yolo):

    global neural_net, ln, LABELS

    weights = os.path.sep.join([yolo, "yolov3.weights"])

    config = os.path.sep.join([yolo, "yolov3.cfg"])

    labelsPath = os.path.sep.join([yolo, "coco.names"])

    LABELS = open(labelsPath).read().strip().split("\n") 

    neural_net = cv2.dnn.readNetFromDarknet(config, weights)

    ln = neural_net.getLayerNames()

    ln = [ln[i[0] - 1] for i in neural_net.getUnconnectedOutLayers()]

In the image processing section, we extract a still image from the video and analyze it to find the distance between the people in the crowd. The function's first two lines specify an empty string for both the width and height of the video frame. To process many images simultaneously, we utilized the cv2.dnn.blobFromImage() method in the following line. The blob function adjusts a frame's Mean, Scale, and Channel.

(H, W) = (None, None)

    frame = image.copy()

    if W is None or H is None:

        (H, W) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)

    neural_net.setInput(blob)

    starttime = time.time()

    layerOutputs = neural_net.forward(ln)

YOLO's layer outputs are numerical values. With these numbers, we may determine which objects belong to which classes with greater precision. To identify persons, we iterate over all layerOutputs and assign the "person" class label to each. Each detection generates a bounding box whose output includes the coordinates of the detection's center on X and Y as well as its width and height.

            scores = detection[5:]

            maxi_class = np.argmax(scores)

            confidence = scores[maxi_class]

            if LABELS[maxi_class] == "person":

                if confidence > 0.5:

                    box = detection[0:4] * np.array([W, H, W, H])

                    (centerX, centerY, width, height) = box.astype("int")

                    x = int(centerX - (width / 2))

                    y = int(centerY - (height / 2))

                    outline.append([x, y, int(width), int(height)])

                    confidences.append(float(confidence))

Then, determine how far apart the middle of the active box is from the centers of all other boxes. If the rectangles overlap only a little, set the value to "true."

for i in range(len(center)):

            for j in range(len(center)):

                close = Check(center[i], center[j])

                if close:

                    pairs.append([center[i], center[j]])

                    status[i] = True

                    status[j] = True

        index = 0

In the following lines, we'll use the model's box dimensions to create a square around the individual and evaluate whether or not they are in a secure area. If there is little space between the boxes, the box's color will be red; otherwise, it will be green.

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            if status[index] == True:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)

            elif status[index] == False:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

Now we're inside the iteration function, where we're reading each film frame and analyzing it to determine how far apart the people are.

ret, frame = cap.read()

    if not ret:

        break

    current_img = frame.copy()

    current_img = imutils.resize(current_img, width=480)

    video = current_img.shape

    frameno += 1

    if(frameno%2 == 0 or frameno == 1):

        Setup(yolo)

        ImageProcess(current_img)

        Frame = processedImg

In the following lines, we'll utilize the opname-defined cv2.VideoWriter() function to save the output video to the provided place.

if create is None:

            fourcc = cv2.VideoWriter_fourcc(*'XVID')

            create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True)

    create.write(Frame)

Testing the program

When satisfied with your code, launch a terminal on your Pi and go to the directory where you kept it. The following folder structure is recommended for storing the code, Yolo framework, and demonstration video.

The yoloV3 directory is downloadable from the;

https://pjreddie.com/media/files/yolov3.weights

videos from:

https://www.pexels.com/search/videos/pedestrians/

Finally, paste the Python scripts provided below into the same folder as the one displayed above. The following command must be run once you've entered the project directory:

python3 detector.py

I applied this code to a sample video I found on pexels, and the results were interesting. The frame rate was terrible, and the film played back in almost 11 minutes.

Changing line 98 from cv2.VideoCapture(input) to cv2.VideoCapture(0) allows you to test the code without needing a video. Follow these steps to utilize OpenCV on a Raspberry Pi to identify inappropriate social distances.

Complete code

import numpy as np

import cv2

import imutils

import os

import time

def Check(a,  b):

    dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5

    calibration = (a[1] + b[1]) / 2       

    if 0 < dist < 0.25 * calibration:

        return True

    else:

        return False

def Setup(yolo):

    global net, ln, LABELS

    weights = os.path.sep.join([yolo, "yolov3.weights"])

    config = os.path.sep.join([yolo, "yolov3.cfg"])

    labelsPath = os.path.sep.join([yolo, "coco.names"])

    LABELS = open(labelsPath).read().strip().split("\n")  

    net = cv2.dnn.readNetFromDarknet(config, weights)

    ln = net.getLayerNames()

    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

def ImageProcess(image):

    global processedImg

    (H, W) = (None, None)

    frame = image.copy()

    if W is None or H is None:

        (H, W) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)

    net.setInput(blob)

    starttime = time.time()

    layerOutputs = net.forward(ln)

    stoptime = time.time()

    print("Video is Getting Processed at {:.4f} seconds per frame".format((stoptime-starttime))) 

    confidences = []

    outline = []

    for output in layerOutputs:

        for detection in output:

            scores = detection[5:]

            maxi_class = np.argmax(scores)

            confidence = scores[maxi_class]

            if LABELS[maxi_class] == "person":

                if confidence > 0.5:

                    box = detection[0:4] * np.array([W, H, W, H])

                    (centerX, centerY, width, height) = box.astype("int")

                    x = int(centerX - (width / 2))

                    y = int(centerY - (height / 2))

                    outline.append([x, y, int(width), int(height)])

                    confidences.append(float(confidence))

    box_line = cv2.dnn.NMSBoxes(outline, confidences, 0.5, 0.3)

    if len(box_line) > 0:

        flat_box = box_line.flatten()

        pairs = []

        center = []

        status = [] 

        for i in flat_box:

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            center.append([int(x + w / 2), int(y + h / 2)])

            status.append(False)

        for i in range(len(center)):

            for j in range(len(center)):

                close = Check(center[i], center[j])

                if close:

                    pairs.append([center[i], center[j]])

                    status[i] = True

                    status[j] = True

        index = 0

        for i in flat_box:

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            if status[index] == True:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)

            elif status[index] == False:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

            index += 1

        for h in pairs:

            cv2.line(frame, tuple(h[0]), tuple(h[1]), (0, 0, 255), 2)

    processedImg = frame.copy()

create = None

frameno = 0

filename = "newVideo.mp4"

yolo = "yolov3/"

opname = "output2.avi"

cap = cv2.VideoCapture(filename)

time1 = time.time()

while(True):

    ret, frame = cap.read()

    if not ret:

        break

    current_img = frame.copy()

    current_img = imutils.resize(current_img, width=480)

    video = current_img.shape

    frameno += 1

    if(frameno%2 == 0 or frameno == 1):

        Setup(yolo)

        ImageProcess(current_img)

        Frame = processedImg

        cv2.imshow("Image", Frame)

        if create is None:

            fourcc = cv2.VideoWriter_fourcc(*'XVID')

            create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True)

    create.write(Frame)

    if cv2.waitKey(1) & 0xFF == ord('s'):

        break

time2 = time.time()

print("Completed. Total Time Taken: {} minutes".format((time2-time1)/60))

cap.release()

cv2.destroyAllWindows()

Why is Social Distancing Detection helpful?

  1. Convincing Workers

Since 41% of workers won't return to their desks until they feel comfortable, installing social distancing detection is an excellent approach to reassure them that the situation has been rectified. People without fevers can still be contagious; hence this solution is preferable to thermal imaging cameras.

  1. Space Utilization

Using the detection program, you can find out which places in the workplace are the most popular. As a result, you'll have all the information you need to implement the best precautions.

  1. The Practice of Keeping Tabs and Taking Measures

The software can also be connected to security video systems outside the workplace, such as in a factory where workers are frequently close to one another. To be able to keep an eye on the office atmosphere and single out those whose personal space is too close to others.

  1. Tracking the Queues

Queue monitoring is a valuable addition to security cameras for businesses in retail, healthcare, and other sectors, where waiting in line is unnecessary. As a result, the cameras will be able to monitor and recognize whether or not people are following the social distance requirements. The system can be configured to function with automatic barricades and digital billboards to provide real-time alerts and health and security information.

Consequences of Isolation

The adverse effects of social isolation include the following:

  • Its efficacy decreases when mosquitoes, infected food or water, or other vectors are predominantly responsible for spreading disease.

  • If a person isn't used to being in a social setting, they may become lonely and depressed.

  • Productivity drops, and other benefits of interacting with other people are lost.

Conclusion

This tutorial showed us how to build a social distance detection system. This technology makes use of AI and deep learning to analyze visual data. Incorporating computer vision allows for accurate distance calculations between people. A red box will appear around any group that violates the minimum acceptable threshold value. The system's designers used previously shot footage of a busy roadway to build their algorithm. The system can determine an approximation of the distance between individuals. In social interactions, there are two types of space between people: the "Safe" and "Unsafe" distances. In addition, it shows labels according to item detection and classification. The classifier may be utilized to create real-time applications and put into practice live video streams. During pandemics, this technology can be combined with CCTV to keep an eye on the public. Since it is practical to conduct such screening of the mass population, they are routinely implemented in high-traffic areas such as airports, bus terminals, markets, streets, shopping mall entrances, campuses, and even workplaces and restaurants. Keeping an eye on the distance between two people allows us to ensure sufficient space is maintained between them.

First Article Inspection: Everything You Need to Know

What is a First Article Inspection?

First article inspections, originally developed for the aerospace and defense industries, are now being used as best practices in other industries. They are an effective way to ensure that the manufacturing process produces an output that meets design specifications. First article inspection helps reduce production delays and waste.

First article inspection is an integral part of the AS9145 process. It is also part of the APQP/PPAP (Advance Product Quality Planning/Production Planning and Control) approval process. The first article inspection report summarizes the design and manufacturing process of the part, including specification requirements, raw materials and associated sub-assemblies.

First article inspections are performed to ensure that the supplier's manufacturing process meets the design specifications. They can be completed by the supplier or the purchaser.

First article inspection is typically performed by obtaining part dimensions using a CMM (computerized measuring machine). Afterwards, the dimensions are compared to the original design. This allows the buyer to identify potential problems early. First part inspection can also be used to detect errors in the operator's process.

FAI works best when used in conjunction with a supplier who has experience in manufacturing precision parts. The advantage of using FAI is that it reduces the number of defects generated in the first place, thus saving money on rework.

First article inspections are also useful in industries where expensive materials cannot be reworked. They are particularly important in the aerospace industry, where accuracy is critical. They help ensure that the characteristics of all components are taken into account. First-part inspections also ensure repeatability of the manufacturing process.

How Do You Do a First Article Inspection?

First article inspection is an important part of the quality control program. It ensures a consistent manufacturing process and guarantees product specifications. It can also help you save money.

First article inspection is a quality control process often used by manufacturers of small, complex parts. It involves using a coordinate measuring machine (CMM) to compare manufactured parts to specifications. The results of the inspection are usually recorded in a first article inspection report.

First article inspection is critical because it provides an objective measurement of the manufacturing process and helps determine if the product meets customer specifications. It is usually completed by the supplier or an approved subcontractor. First article inspections are beneficial to a wide range of industries. They are particularly useful in industries with stringent specifications and requirements. For example, first article inspection is an important part of quality control in the aerospace industry.

FAI is also a useful quality control tool when expensive materials are used. It can confirm that the product is of sufficient material quality and cannot be reworked.

The first article inspection process can be automated. A process can be created that automatically sends the form to the approver. This helps eliminate errors and ensures that no important information is missed. It can also help develop standard operating procedures.

FAI is beneficial because it can reveal problems that are not visible during mass production. It can also reveal changes in operator processes. First article inspection can also help you determine if adjustments need to be made to the manufacturing process.

What is the Difference Between PPAP and FAI?

PPAP (Production Part Approval Process) is a collection of documents used to validate a manufacturer's manufacturing process. It is used to help manufacturers meet customer requirements for product quality and safety. It is a risk identification process that helps reduce revisions while ensuring a repeatable process. It is overseen by the International Aerospace Quality Group.

The PPAP contains a list of test results, manufacturing process details, and quality control plans. PPAP submissions are created collaboratively between the customer and the supplier. The customer must certify the supplier.

Manufacturing industries such as the automotive and aerospace industries use PPAP processes. The checklist identifies the information needed for each stage of the new product introduction process. It also includes a PFMEA, process flow diagram and gauge R&R that must be provided by the supplier to prove that the raw materials meet the customer's specifications.

FAI(First article inspection) is a critical step in the manufacturing process. It checks design and manufacturing documentation to ensure that the process is repeatable and that the product meets the customer's specifications. It also ensures that the supplier's manufacturing process is appropriate for the part.

FAI is also used to verify that external special handling steps have been performed by the supplier. It should be performed after tooling changes, repairs, or design changes. It should occur after the manufacturing process has been stable for a period of time.

After adding a new supplier to the manufacturing process, the supplier must perform a FAI. It would be advantageous to manufacture a sample unit for the customer for evaluation purposes.

The Importance of a First Article Inspection

Performing a first article inspection is an important step in delivering the goods the buyer needs. It helps the manufacturer determine if they are producing the correct parts to specification. Buyers can also confirm that the manufacturer understands their design during the first inspection. It helps reduce manufacturing delays and waste.

Product inspection is performed first before the mass production process begins. These inspections can be performed on parts made by different suppliers or using various equipment or methods of manufacturing. In addition, they are used in the aerospace and defense industries. These are some of the industries that can benefit from the use of first article inspection.

The first article inspection report is an objective proof that the part meets the specifications. It includes dimensional and cavity measurements. The report also summarizes quality control checks. It also includes a table of inspection requirements that includes balloon numbers, associated tolerances and specifications.

First-part inspections are critical in a wide range of industries. They are especially important for manufacturers of small, complex parts with tight tolerances. These inspections are necessary because problems are identified early in the manufacturing process, saving money and time.

If a supplier is responsible for producing large quantities, quality control procedures must be in place. Each product must be manufactured to the specifications provided by the customer. It is more expensive to find problems later in the manufacturing process.

First article inspection services allow suppliers to identify problems before mass production. This saves money because it identifies problems earlier and reduces downtime in the correction process.

First article inspection is performed by qualified personnel who use Coordinate Measuring Machines (CMMs) to inspect manufactured parts. Coordinate measuring machines are the most accurate measuring instruments used in quality control. They are also used to inspect parts that are difficult or time-consuming to inspect.

First article inspection is usually performed at the beginning of a production run. First-part inspection is not required for second and third production runs. However, for new orders, a first article inspection report may be required in some cases. It can also be done by an approved subcontractor.

Companies supplying to government agencies or other regulated industries must be more careful in their manufacturing processes. They must also be more stringent in the quality of their materials. FAI helps them meet these requirements. The process also ensures that all requirements are met and reduces the potential for costly errors.

The cost of first article inspection is usually very low. In major cities in China, India and Vietnam, it typically costs about $299 per person-day. However, additional travel costs may be incurred in other regions. FAI costs must be included in the total project cost.

Many manufacturers in industries such as automotive, aerospace and medical devices use First Article Inspection reports. These reports are very detailed and contain information about the quality of the part manufacturing process.

When Should First Article Inspection Be Performed?

First article inspection is a critical quality control step. It helps ensure that the product meets design specifications. It clarifies expectations and saves time and money by identifying problems early. First article inspection also has advantages in highly regulated industries. First article inspection reports are often used in such industries to ensure that products meet engineering design specifications.

Several steps are required to perform a first article inspection. Depending on the needs of the buyer and supplier, first article inspection can be performed for a variety of reasons. Many industries use first article inspection, including aerospace, automotive and medical devices. It can also be used for purchase orders and procurement planning.

Suppliers and buyers must work together to ensure that the product meets all requirements when performing first article inspection. When a part does not meet specifications, it is usually the supplier's fault. The supplier may need to modify the design or manufacturing process.

Purchase orders, purchase planning and manufacturing can all benefit from first article inspection. Each parameter and step of the manufacturing process should be verified in a report. An automated workflow can generate a first article inspection report. The report can then be automatically sent to the approver.

First article inspection is a quality control process that occurs prior to the start of the batch manufacturing process. It is an objective measurement of the manufacturing process and helps to confirm compliance with engineering design specifications. It also helps to eliminate waste, confirm safety requirements and reduce costs.

What is CNC Machining? | Definition, Processes, Types & Components

Hi Guys! Hope you’re well today. Happy to see you around. In this post, I’ll walk you through What is CNC Machining? It’s Definition, Processes & Types & Components.

CNC (computer numerical control) machining has been around for a while. It is a manufacturing process where machine tools are guided and controlled by computer software. High efficiency and better control make this process ahead of the manual handling of the tools. CNC manufacturing is done by sophisticated, complex machines that guarantee the formation of the final product with high precision and accuracy. Different CNC machines are used to treat different parts, however, each machine makes use of computer-guided software to precisely dictate and handle the machine tools. It is worth noting that the CNC systems are dynamic in nature which means new prompts can be included in the pre-existing code which is edited and programmed by the programmers.

Curious to learn everything about CNC machining?

Well, you’ve come to the right place.

Keep reading. 

Definition

CNC machining is a process that involves the automatic control of machine tools through a computer to shape the material into the required form. During this process, machining equipment like latches, routers, mills, grinders, and drills... run in accordance with computer instructions. After setting up the machine and loading the program into it, the procedure is automatic and doesn't require any human involvement. To create several items with the same accuracy and precision, the production cycle repeats itself to produce the desired shapes. The parts can typically be produced and supplied in a matter of days, saving both money and time. The most cost-effective method for creating unique parts from metal materials is CNC machining.

Don’t get confused between CNC machining and 3D printing. They are different even though both are used to create distinctive shapes. In the subtractive process of CNC machining, the material is taken out of the workpiece to create a certain shape. On the other side, an additive method is used in 3D printing to add material to make precise objects.

Processes in CNC Machining

A vast variety of materials including plastics, metals, composites, wood, foam, and glass, can be machined using CNC technology. The basic goal of this method, sometimes referred to as digital manufacturing, is to produce items that are uniformly precise and accurate.

There are four fundamental processes in CNC machining. A 3D model of the object is first created using CAD software. The second stage involves converting the digital CAD file data into a CNC program, sometimes referred to as G-code. Setting up the machine for the desired actions is the third phase. Finally, machine tools automatically operate on the workpiece to remove material and turn the workpiece into the appropriate shape, 

Find below each process one by one. 

  1. 3D CAD Model Design Creation

The CNC machining process begins with the 3D solid part design. Utilizing CAD software, where the technical details of the pieces are established, 3D modeling is carried out. Notably, when developing 3D items, designers and manufacturers must take the capabilities of CNC machines and their tools into account.

Most tools are typically cylindrical and can only be used to create curved corner portions. As a result, the design process has a limited range of part geometries. The ability of the machine to hold the workpiece and the material's characteristics, such as the maximum part size, the minimum part thickness, and the complexity of the interior features, also play a role in the CNC machining process.

The 3D model of the solid part is produced by CAD software, and it is exported in the STEP or IGES CNC-compatible file format.

  1. Conversion of CAD File

A CAM (computer-aided manufacturing) program processes the created 3D CAD file to extract the part information and produce programming code known as G-code. This code specifies the operations carried out on the solid material to produce the special portion. The timing of the tool movement, the depth of the cut, the path the tool follows when it is turned on and off, and other instructions are applied to the tools in this area to remove material from the solid workpiece and produce the desired shape.

The worker feeds the G-code into the machine after converting the CAD file.

  1. Getting Ready Machine Set-up

Before the employee applies the program to the tools, the machine needs to be set up properly. This entails tightly holding the workpiece using the spindles of the machine. The overall machining process will be impacted if the holding device fails to keep the material in place. Therefore, ensure that machine spindles operate precisely with no space for error.

Additionally, make sure the appropriate instruments, such as drill bits or end mills, are attached properly. Once the machine is configured, the employee uses the G-code that is provided to carry out the basic tasks programmed into it.

  1. Execution of Machine Activities

This is what we have done so far. We have created the CAD file and converted it into G-code. Then make the setup. 

Now the real process begins. 

In this stage, the worker initiates the computer program that enables the tools to conduct specific operations on the solid material. To create specific shapes, extra material is eliminated from the workpiece. Plastic consumer goods, simple wooden decorations, steel aerospace parts, and intricate metal automobile parts can all be produced with CNC machining.

A variety of industries including agriculture, construction, aerospace, and more use CNC machining – a digital production technique. The technique includes numerous computer-controlled automatic machining operations. The following mechanical processes are frequently used in CNC machining:

  • Drilling

  • Milling

  • Turning

As the name suggests, drilling is the technique of making several cylindrical holes in the workpiece. The drill is used in this process parallel to the workpiece. The drill bit revolves while exerting pressure vertically on the workpiece plane when the operator runs the program. The drill bit produces holes with a diameter equal to its width. You can choose from a variety of drill bits to treat the material's surface. Using specific work-holding devices and machine settings, you can do angular drilling operations in addition to vertical drilling operations.

Multi-point cutting tools are used during the milling process to trim away excess material from the workpiece. The milling process is separated into two primary stages based on operational capabilities. The first is face milling, in which the tool carves solid material from shallow, flat surfaces. The second method is called peripheral milling, and it involves making deep slots and threads in a solid workpiece using a tool.

Turning is a type of CNC machining where the material is removed and the required shape is formed using single-point cutting tools. For turning operations, where the cutting tool is applied linearly to the solid rotating object, CNC lathe machines are employed. The turning process creates slots and taper threads.

Types of CNC Machining

Hope you’ve got a brief idea of what CNC machining is all about. In this section, we’ll discuss the types of CNC Machining. 

In particular, CNC machining is divided into 5 different types that are performed on 5 different types of machines.

The main aim of every machine is to reduce human input and make the process automatic with instructions from the computer. CNC machines are preferred over non-programmable machines since they can produce parts in volumes in less time with better precision and accuracy. 

Read on to find out the five types of CNC machines and how they work. 

  1. CNC Lathe and Turning Machines

CNC lathe and turning machines are mainly known for their ability to rotate objects during the machining process. These machines feed their cutting tools around the revolving bar stock in a linear motion, removing material from the circumference until the required diameter is achieved. One of the key benefits is that they can easily position the X, Y, or Z axes while doing a variety of jobs. These axes allow the machine to move the component as per its geometry.

The desired internal and external features of the object can be formed using these machines including reamed holes, drilled holes, threads, tappers, taping, broaches, and bores. 

CNC Lathe Machine is divided into four main parts:

  • Main Spindle

  • Guide Way

  • Chuck

  • Headstock 

The main spindle is composed of a spindle drive system and spindle assembly. The CNC machine tool comes with some moving parts including chuck, gears, motors, etc. Moreover, the spindle assembly also includes the C-axis drive that is mainly used to position the material.

Guide way ensures the smooth cutting process by allowing the tool to move vertically and horizontally. 

Attached to the main spindle, a chuck is used to tightly grip the object to be machined. Both the workpiece and chuck rotate with the help of the spindle. 

The headstock, which houses the primary motor, is used to hold the main spindle, to which the chuck is attached.

  1. CNC Milling Machines 

CNC milling machines come with a range of cutting tools that move along one or more axes with the main purpose to remove extra material from the object. In the CNC milling machine process, the workpiece remains stationary while the machine rotates the cutting tools that form the material into the desired shape.

These machines are used in scores of industries including FMC manufacturing, oil drilling, automobile, shipping, aerospace, and precision engineering sectors. 

The more advanced CNC milling machines, also known as CNC Machining Centers, are capable to perform along multiple axes. The precision and accuracy of these machines can be achieved with pallet changers, innovative coolant systems, automatic tool changers, and advanced software. 

How it Works?

The CNC milling process starts with mounting the part to be machined on the top of the machine table. You can use a vice or fixture to hold the workpiece in place or you can clamp it directly on the table. 

After that, the spindle (moving part) with the cutting tool is either positioned vertically or horizontally. In that setup, the tool can begin cutting and shaping operations at various X, Y, and Z positions on the workpiece. While doing so, the table may either fix, mount, or move the workpiece in a linear direction toward the spindle containing the cutting tool. As a result, the material will be removed to achieve the appropriate shape for the machined object.

  1. CNC Laser Machines

These machines use high-power, focused laser beams to accurately cut, mark or engrave a material to produce desired shapes. The sophisticated design and operation of these machines perform the machining process without errors while creating small holes and complex shapes. 

CNC laser cutting machines are mainly divided into three types.

  • CNC CO2 laser cutter

  • CNC crystal laser cutter

  • CNC fiber laser cutter

CNC CO2 laser cutters exhibit high power output capability and high efficiency, hence most commonly used to make custom shapes.

CNC crystal laser cutters show high laser power compared to CO2 laser cutters, thus allowing you to cut and shape thicker metal materials. In these cutters, the laser beam is made of crystals like neodymium-doped yttrium ortho-vanadate (Nd:YVO) or neodymium-doped yttrium aluminum garnet (Nd:YAG).

The CNC fiber cutters use a bank of diodes to produce a laser beam where fiber optic cable is used to eject the laser beam. In particular, for materials with a thickness of less than 5 mm, fiber laser cutters enable a quicker and more precise cutting process than CO2 laser cutters.

How does it work?

The CNC laser cutting process is slightly different from the conventional CNC machining process since it doesn’t involve direct contact with the workpiece, hence a thermal-based process. The laser cutting tool contains a laser head that houses a nozzle and laser cutting lens. 

The nozzle projects a high-intensity laser beam on the component to be machined, melting and cutting the extra material from the component to form the required shape. Once the material is removed, the compressed gas is applied through the same nozzle to cool the lens and extract the vaporized metal from the workpiece. 

  1. CNC Electrical Discharge Machines (EDM)

The EDM, also known as spark machining or spark eroding, makes use of highly controlled electrical sparks to shape the material into the required form. Again, this is a non-traditional, precision machining method used to manipulate the material. The electric sparks produced in this process are near 8000º C to 12000º C. This process is typically employed for creating deep cuts and sharp corners that are otherwise impossible to achieve from the CNC milling and CNC turning process.

In this process, the machine is designed to emit an electrical discharge from the electrode wire that generates a great deal of heat and a component is positioned underneath the electrode wire (up to 21,000 degrees Fahrenheit). To generate the required shape, the material is melted or washed away with liquid.

EDM is mainly divided into three types:

  • Die sinking EDM

  • Wire EDM

  • Hole drilling EDM

In die-sinking EDM, graphite or copper electrodes are used while an electric spark is induced between the electrode and the part to be machined. It is the best method to produce parts with intricate cavities. Sometimes it’s difficult to create sharp internal corners with regular CNC machining. This is where Die sinking EDM comes in handy.

Wire EDM is best suited for creating extrusion dies. The mechanism is the same as die sinking, however, in wire EDM, fine electrically charged wire is used instead of a die. This charged wire also works as an electrode and is very thin, with a diameter ranging from 0.05mm to 0.35mm. This process is used for creating incredibly precise cuts.

Hole Drilling EDM, as the name suggests, is employed to create holes. The basic principle is the same as die sinking, however, the cut is created through a pulsing cylindrical electrode. This technique has been essential for the development of high-temperature turbine blades because it enables the production of extremely complex cooling channels inside the turbine blades.

  1. CNC Plasma Cutting Machines

Plasma cutting machines are another type of CNC machine used to precisely shape the workpiece. These machines use high-powered plasma (electronically-ionized gas) torch that is controlled and guided by the computer. 

How it Works

The plasma torch is gas-powered and comes with temperatures up to 50,000 degrees Fahrenheit. The high-temperature plasma strikes the material and instantly melts it, creating deep cuts with better control and accuracy. The materials that can be treated through plasma machines include copper, brass, aluminum, stainless steel, and steel. They all are electrically conductive materials which is the basic requirement for machining through plasma cutting machines.

Plasma-cutting systems offer fast cutting speeds and throughput along with a cheap cost per millimeter of material cut. These high-definition systems remove the need for secondary procedures on processed parts.

Furthermore, CNC plasma cutting is a remarkable option for applications in both large-scale enterprises and tiny hobbyist shops due to its fast speed and high accuracy.

Components of CNC Machine

The CNC Machine features 12 common components as below:

1: The Input Device

The part programming data is applied through input devices. The input devices are mainly divided into three common types:

  • Punch tape readers
  • Magnetic tape readers
  • Computers connected via RS-232-C

2: Machine Control Unit

This is the main part of the system, also known as the brain of the machine. The MCU is responsible for controlling all machine operations. Its main purpose is to decode the instructions provided by the programmer through the computer. The auxiliary control activities are all performed through this unit, like tool change, spindle on/off, and applying coolant. 

It provides the axis speed order to the amplifier circuit powering the spindle mechanism. It receives feedback signals showing the position and speed of each drive axis.

3: Machine Tools

A CNC machine tool comes with a sliding table and a spindle to control position and speed. 

The machine can work around the X, Y, and Z axis which mainly handle the movement of the tables, while the Z axis is used to manage the spindle.

4: Bed

The Bed is composed of hard material like cast iron and is responsible for carrying all the machine weight, making sure each machine part stays in place when the machining operation is performed over the unit. 

5: Head Stock

One of the main components is the headstock, where the workpiece to be machined is fixed. A headstock also houses the electric motor that powers the main spindle.

6: Tailstock quill

The tailstock quill is used to place the workpiece between the headstock and tailstock.

7: The Tailstock 

This part offers more grip to the workpiece during operations like turning, threading, and noodling.

8: Chuck

The chuck is used to give space for fixing the tool and is mounted on the main spindle.

9: Pedal

Pedal, also known as Footswitch, can open and close the chuck to grip the workpiece. 

10: Display Unit

The display unit is a monitor that constantly shows important information, programs, and instructions on the screen. 

11: The Drive System

The drive system of the CNC machine features an amplifier circuit, lead screw, and ball drive motors. The MCU plays a key role in providing the signals to the amplifier circuit.  When the control signals are amplified, they turn on the drive motors. 

12: Feedback System 

A feedback system, also known as a measuring system, is equipped with transducers that are the sensors of the machine. These motion and position sensors continuously monitor the movement and location of the cutting tool, making sure the tool properly cuts as per the instructions given by the computer. This feedback system runs in a loop, continuously comparing the response signals with the reference signals and adjusting the tool movement and location accordingly. 

Elements of CNC Machine

The CNC machine comes with the following elements:

  • Program

  • Tape Reader

  • Mini-computer

  • Servo system

  • CNC machine tool

      Program

      The keyboard is used to enter the program into the computer. The program is the code used to guide and control the machine's functions. The common CNC codes include: G code, N code, F code, XYZ code. 

      Tape Reader

      The tape reader serves as a storage device for the machine. It stores the code to be performed on the machine tools. The programmer can edit the code stored in this device.

      Mini Computer

      This is also known as the machine control unit. It is mainly used to decode the program information and decide the spindle speed, start and stop the coolant, turn on/off the machine spindle, control the feed rate, and change the workpiece and a few other instructions to properly handle the tools as per requirements. Mini Computer exhibits diagnostic software that identifies the overall health of the machine and adjusts the machine's activities accordingly. 

      Servo System

      This system is directly connected with the feedback mechanism that receives the control signals and sets the output as per requirement. 

      Servo system features:

      • Servo Motors

      • Feedback devices

      • Ball screws

      CNC Machine 

      This is the entire machine unit where the workpiece is machined and the final product is obtained after the machine operation. 

      Difference between CNC and NC Machines

      The NC stands for numerical control. It is also an automatic manufacturing process but here the programs are in numeric, alphanumeric, or binary language. The NC machine has no computer and no feedback system and is less sophisticated than CNC machines. A special inserting device is used in NC machines that store the main program. 

      CNC machines guarantee the production of parts with high precision and accuracy, while on the other hand, NC machines don’t produce parts with fine quality.  

      In CNC machines operation parameters can be changed while NC machine doesn’t allow you to change parameters. 

      The NC machine doesn’t run in a continuous loop to produce parts with the same accuracy while the CNC machine can run repeatedly to produce scores of parts with similar specifications. 

      CNC machines are costly compared to NC machines and also the maintenance cost is very high.

      Moreover, once the machine is set up and the program is fed into the CNC machine, a single person can perform a range of tasks. This is not the case with the NC machine. More labor is required to do each task, hence more labor cost and more time-consuming.

      Industrial applications

      CNC systems are used in a range of industrial applications. A few common industries include:

      • Electrical discharge machining

      • Metal fabrication

      • Automotive

      • Agriculture

      • Electronics

      • Manufacturing

      From higher flexibility and repeatability to consistent quality and increased productivity, these machines provide some key benefits over traditional machines.   

      Conclusion

      There is no denying that CNC machines are the future of the manufacturing industry. 

      With the advancement in technology, companies are creating more space for automatic technology that involves minimum input and delivers maximum output. 

      CNC machines, no doubt, require more initial costs for setup and maintenance compared to the traditional manufacturing process. However, once the machine system is properly installed, it reduces human involvement and requires less time and cost to produce more parts with similar properties. 

      If you’re still using traditional methods to produce parts, it’s about time you consider CNC machining in your industry. The sooner you make a shift, the better.

      That’s all for today. Hope you’ve enjoyed reading this article. I’d love to hear your valuable input regarding CNC machining. And if you have experienced this process before, share your insights in the section below. Until next time. Take Care.

      How to use MATLAB Operators?

      Hello learners welcome to the next tutorial on MATLAB where we are learning about this excellent environment in detail without skipping anything. Last time, you have seen the data types and their detail through practical implementation and this time, you will get information about the operators used in MATLAB and the text-related information in an efficient way. By the end of this lecture, you will be able to answer the following questions:

      • What are the operators and can we use operators in MATLAB?

      • How can you implement the arithmetic operators in your MATLAB?

      • What is the significance of the relational operator?

      • What is the detail of the logical operators in MATLAB?

      • What are bit-wise operators?

      • How can you give a brief introduction to the short circuit operators?

      All of these are important questions not only in programming in the MATLAB language but this is also related to other mathematics and related fields. In order to understand well, I’ll suggest you open your MATLAB software and practice every case on your own because it is super easy to work with the operators in MATLAB even if you are new to this programming environment. 

      Introduction to Operators in MATLAB

      An operator is a symbol that instructs the compiler to perform numerical or logical operations. MATLAB is designed to work primarily with whole matrices and arrays. As a result, MATLAB functions can operate on both scalar and non-scalar data. For a detailed introduction, have a look at the statement given next:

      "The term operator refers to a symbol in computer programming and mathematics that is used to perform specific logical and mathematical operations. It can also be defined as a personification of an action."

      So, we can say, you have used the operators knowingly or unknowingly hundred or thousands of times in different software and today, we are just relating all the procedures to MATLAB and will learn what can we do with these operators. 

      As we have used the basic operations on the matrix many times so, we will be more involved in a little advanced example this time. 

      Using Operators in MATLAB

      The procedure to use different operators is somehow the same as in the real life when we use them in our notebook in mathematics or related subjects. Basically, we divide the operators in MATLAB into the following categories:

      • Arithmetic operators

      • Relational operators

      • Logical operators

      • Bitwise operators

      All of these will be discussed in detail and we believe that most of them are known to you so for your practice, we will have more focus on the examples of each case. In addition, you can also make your own matrices and arrays in addition to my example to have fine practice and it is also fun.

      Arithmetic Operator

      The first and the easiest operator is, as you can guess, the arithmetic operation in which we use the basic operations of mathematics through these operators and therefore, this will be easy for you to understand. But here, the new thing is, the arithmetic operations are categorized into two classes:

      • Matrix arithmetic operators

      • Array arithmetic operators

       The introduction of both of these are self-explanatory but when we talk about the difference between them, we come to know that if the operator is applied to the matrix then it is the matrix arithmetic operation and vice versa. Another point that differentiates between these two is, we use array arithmetic operation, then we use a dot between the symbols of the array to highlight the procedure. The detail of each operator is now given below:

      Addition Operator

      As you can guess, this operator is denoted by a plus sign between the two values to be added and it is the simplest and most frequently used operator. The condition is applied on this operator according to which, both the values (either in MATLAB or simple additional values) must be of the same size if they both are vectors otherwise, if one quantity is a scaler, then it will be added to every member of the matrix. 

      Subtraction Operator

      The subtraction operator is the same as the subtraction in the real world done by us. It also follows the same condition as the additional operation. But you must know, it also includes the negative values in it because many times, the larger value is subtracted from the smaller one we get the negative values in matrices or arrays.

      Matrix Multiplication Operator

      Here comes a slightly different operator than the simple arithmetic operation of the daily world. We can use this operator if and only if the number of rows of one matrix is equal to the other to be multiplied. Otherwise, the same as the other operators, the results are impossible to get. 

      If A and B are two matrices then C, which is the resultant of the multiplication can get as

      C=A*B

      The reason why we are checking the formula of this operation will be clear to you when you will read the next section. 

      Array Multiplication Operator

      There is a bit of difference between this operator and the one discussed before. In this case, each and every element is multiplied by the corresponding element of the other. It is denoted by the dot between the signs of the matrices. 

      If we take the same example as given above, we will denote the array multiplication as:

      C=A.*B

      Matrix Right Division

      The right division of the matrix can be explained well with the help of the example that if A and B are two metrics then their right division is obtained by the following expression:

      C=B/A=B*inv(A)

      Array Right Division

      Just like the array multiplication, the array right division method includes the dot sign between the arrays and we can understand this concept while looking at the expression given next:

      C=B./A

      Matrix Left Division

      Let’s say that if A is the nth order matrix and B is a single column metric then their division, denoted by C=A\B is equivalent to CA=B.

      Array Left Division

      In this type of MATLAB operatorA.B is the matrix with elements B(i,j) a(I,j), where A and B must be the same size.

      Power of the Matrix

      The power of the Matrix is obtained when each Element in the matrix is multiplied by itself equal to the number of the power written just at the upper right corner of the matrix. You can perform this operation by using the A^n sign where n is the power of the matrix.

      Transpose of the Matrix

      You know the transpose of the matrix and its procedure. But in MATLAB, it's more simple and you can easily get the transpose of the Matrix by Using the A’ command where the A is a matrix. 

      Relational Operations in MATLAB

      A relational operator determines the relationship between each element and two arrays. If a relation exists, the value is returned as true or false.

      The operator returns an array of the same size with the values true or false depending on the outcome of an operation. These operators can operate on both scalar and non-scalar data:

      1. < is called Less than

      2. <= is called less than equal to

      3. > is the sign of greater than

      4. >= is a sign greater than or equal to

      5. == can be stated as equal to

      6. ~= refers to not equal to

      Logical Operations in MATLAB 

      The logical operations are somehow different from the first two types. In these types of operations, only two possibilities are there. Either you get 0 or 1. We hope you are aware of the boolean expressions and by connecting the discussion with them, we get the idea that:

      "The logical operations in MATLAB follow the logic of the boolean operations and therefore, the results in such calculations are always either 0 or 1 and therefore, we get the true or false conclusion."

      If we talk purely about MATLAB, we come to know that there are three types of logical operators and functions listed below:

      1. Element-wise logical operations

      2. Bit-wise logical operations

      3. Short circuit logical operations

      Element-Wise Logical Operations

      These are the operations that take the elements of all the cases and perform the procedures separately. Three types of procedures are listed in this type and operators used for different processes are & (AND), |(OR), and ~ (NOT). Moreover, XOR operation is also included in the same category. This will be clear when you will see the representation and the quick revision of the results related to these operators. Suppose we have two elements with the following values:

      X=[0 1 1 0 1];

      Y= [1 1 0 0 1];

      Then, the result of each element-wise logical operation will be:

      Operator Name

      Symbol

      Description

      Result

      AND

      &

      It gives the value 1 only if both the elements are one, otherwise gives zero. 

      X & Y= 01001

      OR

      |

      It gives the value 1 every time when any of the elements are one, otherwise gives zero. 

      X | Y = 11101

      NOT

      It gives the opposite result all the time and it is a unary operation. 

      ~X = 10010

      XOR

      It gives the value 1 every time when the elements have the same value. If they have opposite values, then it is always zero.

      X⊕Y=xor(X,Y)=10100

      One thing that has been noticed here is, as we said earlier, the values in the logical functions are always 0 and 1 therefore, we have also used only these two numbers in the elements and got the results with the same results.

      I hope you now have the best idea about the calculations. Let’s move towards the next type.

      Bit-Wise Operator

      The bit-wise operation, as the name suggests itself, is used when there is a need of bit by bit calculations. Same as in the previous case, the functions are shown with the help of signs and by looking at the table explained below, you can get an idea of the working of each operator.

      P

      Q

      P & Q

      P | Q

      P ^ Q

      0

      0

      0

      0

      0

      0

      1

      0

      1

      1

      1

      1

      1

      1

      0

      1

      0

      0

      1

      1

      Matlab provides the following bitwise operators: 

      • bit and (a,b) – Bitwise AND (integers a and b).

      • Bitmap (a) – It is used to bitwise the compliment of a.

      • Bitget (a , pos) – Get bit at a specified position, in the array a

      • Bitset (a , pos) – set bit at a specified location of a

      • bitShift (a,k) – It is used to get the equivalent results as multiplied by 2k. Therefore, if k is negative, it shifts right, on contrary to this, if k is positive, it shifts to the left position.

      • bitor(a, b) – The operation of this operation is Bit-wise XOR of integers a and b

        Short Circuit Operator

        In addition to the general operator describe before, we have some more interesting operators as well. The operators listed below perform AND and OR operations on logical expressions, including scalar values. They are short-circuiting operators because their second operand is calculated only when the first operand does not fully determine the output.

        &&

        It gives the value of 1 only if both operators give the result 1 otherwise it is zero.

        ||

        It gives the value 1 if either or both inputs are one. We get the contrary results otherwise. 

        Trus, we have seen a lot of operators today that are helpful to understand the introduction of the operators in MATLAB. Many of these have the same symbol and representation of the operators and results. We have seen arithmetic operators, relational, logical, bit-wise, and short circuit operators. It is important to mention here that other operators such as set operators are also included in this learning but I have not mentioned them because these are less known and less used operators in MATLAB. We’ll discuss them in some other tutorial. For now, it is enough to have this information and your homework is to perform all the remaining operators that I have not shown you in MATLAB.

        How to use Data Types in MATLAB?

        Hey geeks, welcome to the next tutorial about MATLAB software and language. In this series, we have been working on MATLAB with the basic information and in the previous lecture, we worked deeply with the workspace window and learned about the functions and variables that are commonly used when we are dealing with the data in the command prompt. In the present lecture, we are dealing with the data types in MATLAB. This is related to the command prompt window but the reason why I have arranged this lecture after the workspace practice is, there will be different steps where the usage of the workspace will be included. Other details will be cleared when you will take this lecture yet, have a look at the list of content that will be included in this tutorial:

        • Introduction to the data types.

        • What are some important data types that we will use in MATLAB coding?

        • What is meant by the numeric and text data types?

        • How can we make tables in MATLAB?

        • Why data types are important in programming?

        • How can you say that different programming languages have different data types?

        What are Data Types

        In almost every programming language, the data types are the important topics and these do not end with a single lecture, but knowingly or unknowingly, you have been using these data types in the practice of your MATLAB codes. So, first of all, I am going to provide you with the proper definition of data types:

        In programming, a data type is a classification that specifies what type of value a variable has and what mathematical, relational, or logical operations can be performed on it without causing an error.

        If this definition seems difficult to you then do not worry, all the details will be clear to you when you will see the example of each of its types. When you use any type of data in your programming language, it is not of the same type but varies according to your needs and requirements. There are several data types but we will discuss the basic and most important in this lecture so we may elaborate on each and every type effectively. But before going into the examples, I am dividing the whole languages into two main classes:

        1. Strongly typed programming languages

        2. Weakly typed programming languages

        Both of them have different ways of implementation, so have a look at them.

        Strongly Typed Programming Language

        Strongly types data types are the ones in which there is a restriction of using the particular variable is used according to its data type. You must know, MATLAB is a strongly typed programming language because you can not connect irrelevant data types together in it but you have to use the same data type all the time when connecting two or more together. 

        Let us have an example. We have seen the concatenation process in the previous lecture where two digits may have the arithmetic operation if they belong to the same class that is the same data type. So, if you try to connect an integer with the string, it will throw an error. 

        Weakly Typed Programming Languages

        The weakly typed data type, contrary to the first case, can be used in an easy way because there is the independence to use the different data types together with the help of any operation. It happens in only a few programming languages and it is not relevant to our MATLAB so I am not explaining it more. 

        List of Data Types in MATLAB 

        Finally, I am going to describe the detail of almost all the data types that you are going to use in the MATLAB throughout your course and with the help of this knowledge, you will be able to use these data types according to your needs and at the final result, you will code in the best way. So, have a look at the detail of each data type. 

        Numeric Types

        The first and most basic type that we all know is the numeric type. Here, if you are new to programming, I must mention that numerics also has different classes in it and two of them are:

        1. Integer

        2. Floating Points

        3. Single

        4. Double

        Integers: 

        The numbers that mostly we use in our daily life are integers we have read the definition of integer in our begging classes that these are whole numbers ranging from positive infinity to negative infinity but we are mentioning here the definition because I want to make sure you use the code without any confusion.

        Floating Points:

        The floating points are the numeric types that contain the part, less than one in them, in addition to the whole number. This portion is then added in the form of points. To memorise well, you can think that every integer has zero additional points than a whole number and the floating point digits additional to that whole number. 

        Single:

        It is the array of single precision numbers that occupies less memory because it just stores the first digit after the point. Basically, it is the subclass of the floating number and is less accurate than the other case that we are discussing next. It is less likely to choose and if the user is not using scientific information, then they use the single integer to fix less memory for their data type. For instance, the result of the calculation will only be shown just after one point such as 12.3 only.

        Double:

        It is also the class of the floating point that stores more memory than the single data type. It is more accurate because it can store the two numbers after the floating point. For example, if you choose the double floating point, it will provide you with the results as 12.34. The numbers having a value more then this will require to be saved int eh data type of character or string according to the length of the number.

        IntX numbers:

        These are the interesting types of data in which users may get the integer type of his/her own choice. There are different int X numbers where the X varies from 8 to 64. So, by applying the numbers 8, 16, and 64 with the X separately, you can fix the memory space of your own choice where you can easily declare the variables. 

        For example, if you want to declare the variable of the size 8 bits, you will write the following command: 

        int8(value)

        It will create a space of 127 numbers. The total size of this 8 bits data is one byte and it occupies the space to accommodate 0 to 127 numbers. By default, if you do not specify, it is the unsigned data that starts from 0 to 127. 

        If you want the numbers with the same memory size but the ones that include the negative sign as well, you can do so by changing the command to:

        uint8(value)

        Now, I am writing both these commands in the command prompt and with the help of the workspace window, you can compare the values stored in both these cases.

        Similarly, you can check for the int16 and int64 as well and the workspace window will tell you about the detail of each and every case with the signed and unsigned value. 

        If you do not want to use the workspace window, you can find the details of your data type with the help of whos command that we have learned in the past lecture.

        So in this way, it becomes easy to search and get the results of details of any kind you want about the particular data type. 

        Class of The Data Type

        It is time to tell you about a useful and simple command to get the class of the data type easily if you do not remember the size or data type of your variable. So, the syntax to do so is:

        class(variable)

        Where the variable amy be any data type, this keyword will help us to find its class.

        Keep in mind, the A varialbe was declared by you before using this class keyword otherwise, you will ge tthe error.

        Text Data Type

        When using the text in the code in any way, you have to use the alphabet, as expected. But, you must know that there are also two types of text data types that are, the same as the numeric type, have a slight difference between them and we use them according to the need of time. Here are these two:

        1. Character  type data

        2. Sring type data

        CharacterText:

        The character type data is used when we want to declare the variable of the text with relatively less memory space. In simple words, when we want to declare a single alphabet or small sentences, we use the character. The declaration for the characters is as follows:

        A=’Tom’

        Where the single quotation tells the compiler that we want the space for the character text.

        String Text: 

        The string text, as you can expect, has more memory space than the character. These concepts are discussed in the last lecture so I am not going to give you unnecessary details and examples.

        Tables

        Row and column variables are present in the table. Each variable can have different data types and sizes, but they must all have the same number of rows. A variety of functions are used to access data in order to create, edit, and read table data.

        Syntax

        A=table(column1,column2,....,column(n))

        Here, you can easily declare the column's name and after that, you can enter the data according to your choice.

        Structure Data Type

        Data containers are used in the structure to group related data and their types, which are referred to as fields. Fields can hold any type of data. The dot notation is used to access data in structures.

        Why We Use Data Types in Programming?

        We know you have an idea that data types are important in programming languages yet, I always use the explanation of the importance of the topic that is being discussed. 

        • The data types are used to occupy a specific amount of the data according to the need of the user. For example, there is no need to reserve the memory space equal to the string data when you need only the data of a single integer. In this way, the program runs slowly and this problem is unbearable if you have a large data in the program or have a slow system than required. 

        • The data types make the code more organized and clean. 

        • With the help of data types, the path of the program is more clear that how the flow is being used from start to end when you are programming your code. 

        • The readability of the program is enhanced with the help of clearly defined data types. 

        Data Types in Different Programming Languages

        It is an interesting question that must be cleared when dealing with programming languages. We know you have a basic knowledge of programming languages and therefore, I am not explaining from the scratch. But, you must know that it is not necessary that all the programming languages are based upon the same data types. Usually, the code of the programming language is distinguished by its data types and the keywords that we use with the specific syntax.

        Hence, it was a detailed lecture on the data structure where we learned a lot about the data types and we have learned a lot of infprmation in differnet ways. All the work was practiacally performed but if you find that something that needs implementation, you should practice it by yourself as your homework. We had a lot of discussion related to the different case where we use some special keywords to find the type or the relation of different data types. Hence, you can now designed you codes according to the required data type. Stay with us for more interesting tutorials. 

        How to use MATLAB Workspace?

        Hello, readers. Welcome to the MATLAB tutorial, where you are learning the basics to advance information about MATLAB without discussing unnecessary concepts. In the last lecture, there was a discussion about variables and their declaration, usage, and types in detail using the MATLAB command prompt. This time, you are learning the workspace window of MATLAB. Usually, people while learning ignores this window because they do not bother about what is happening in it, but the experts know that by applying the simple rules in the workspace window, they can easily get better results. At the end of this lecture, you will be able to answer the following questions:

        • What is the workspace window of MATLAB?

        • How can you save the files from the workshop in different ways?

        • What is the method to load the files of the workspace window?

        • How are characters implemented in MATLAB?

        • What are the details of using the string in the command prompt?

        • What are some of the important functions of MATLAB?

        Workspace Window of MATLAB

        The workspace window is a type of window that appears in the upper right corner of the MATLAB window. At first, the focus of the user is usually on the command prompt, and hardly anyone observes the presence of the list of variables in the workspace window that they are declaring. So, the user is not required to store the variables separately in this particular window. Keep in mind, the variables in this window can lose their existence when the environment is closed, the same as in other windows. Yet, the reason why I am mentioning this point here is, the variables are saved in this window on their own, and even after we clear the screen of the command prompt, the variables are still shown in the workspace. So, we can say, even if the command prompt does not show the values of the variables, you can find them in the workspace window with all the details of their values and dimensions. 

        Now, it is important to show you the above discussion in action with the help of an example. The workspace window has two portions and they are labelled as names and values. Here, we are declaring the variable with the name A in the command prompt and all its data is saved in the table-like format in the workspace.

        Notice that when we write clc in the window, we can still see the value of A in the workspace. So, whenever you want the value of A again, you can simply write A in the command prompt and you will get your required value. 

        Using Files in Workspace

        As we have said earlier, the data in the workspace vanishes once you close MATLAB. So, to save your data, you can easily use it in the future if you want. To do this, you have to follow these steps:

        • Go to the home tab. 

        • Search for the “save workspace” option.

        • Give a meaningful name to the file so that you may remember the name to search for it in the future.

        MATLAB will save this file with the extension .mat.

        Once you have saved it, you can easily reuse this file whenever you want by merely going into the “Open” option and selecting your desired value, The procedure is the same as the other files in the computer system. 

        Saving the Documents Through Command

        Another way to do the same task is to use the command prompt to save the file. For this, you just have to write the command in the prompt and I found it more interesting than the first procedure. So, to save the file in the command prompt, you can follow the command given below:

        Save MyFile

        Once you save your file, the same file with the name chosen by you will be shown in the “current folder” window of your MATLAB. In this way, it becomes super easy to use your required folder again.

        How to Load the Files in Workspace

        Another command is used to load or open the file saved by you the previous day. So, the command used for this purpose is given as:

        Load MyFile

        Keep in mind, you have to follow the rule that the name you are specifying must be the name of the file you have same. The spelling and the case size of each and every word must be the same. So, I usually prefer to load the file from the current folder window where I can find all the files saved by me arranged alphabetically.

        Usually, people face the issue of an error when they choose the load command on the file saved by them.  Or sometimes, the user gets the error of saving the file in the form of a folder. The issue may be resolved by using the correct current folder from MATLAB. If you are facing the issue as shown in the figure, maybe you are selecting from the wrong folder. The best way to check it is to notice the path of the folder where your files are being saved while saving the file.

        Here, before going into other details, I consider it important to tell you about the tabs and the setting of the workspace window. It may be the issue with your MATLAB that you do not get all the required tabs that is shown in the tutorial, so if you want to add more, you can simply do s by going into the settings and choosing the best tabs for you.

        Character in the MATLAB

        Characters in MATLAB can be used as they are written in normal life. In contrast to most other programming languages, such as C++, you do not have to specify the type of content you want to add to the compiler. You just have to write it between the inverted commas and you are good to go.

        In some tutorials, you will also observe a single semicolon at the end of this command. I am not using it because it is up to the choice of the user, so I do not prefer to have additional words in my code. 

        A special case comes into observation when we want to add the double quotation in our string message but are not able to do so. Then, the user may use the double quotation mark twice.

        This case is important when you are writing long sentences with information about a particular person or thing. 

        Concatenation of The String

        It is time to discuss an interesting and useful process while using the strings in the array. If you are familiar with the process of concatenation, then you must know that:

        “The term "concatenations" means to merge two things together, and in programming languages, it is the process of connecting two strings together in a single sentence.”

        You can save the values of the variables and then use them with each other with the help of concatenation.

        This helps a lot when you have to use the different types of numbers again and again in different ways. 

        Character in the Form of Array in MATLAB

        To store and arrange the data in an organized way, arrays are used. If you have great numbers of strings and want to store all the data in the array format, you can do so as you were dealing with the normal numbers before. Yet, this time, you have to put quotation marks before and after the character work or sentence. 

        Strings in MATLAB

        Strings can be used as characters in MATLAB, but these have two very basic differences that are mentioned below:

        Character

        String

        It has less size than a string.

        It is bigger than the character.

        It is assigned by using a single quotation mark. 

        It is assigned by using the double quotation mark. 


        Usually, sentences are used in the strings because they save a large amount of memory, and characters are used in cases where single letters are to be used. Basically, a string in MATLAB is an array of characters. Usually, we can memorize the difference between different data types by keeping in mind, when we deal with the alphabet, we use either strings or characters, and usually, a string is considered the sentence that has to be printed on the screen.

        Important Functions In MATLAB

        There are different functions of MATLAB that you must know if you are dealing with large data such as strings and characters, For your information, we are discussing some of them.

        • Display function

        • Clear function

        • Maximum Function

        • Minimum function

        • Whos function

        The details of both of them are given here:

        Display Function

        The display function, as the name suggests, is used to display the results, function, or anything that is fed into it. The main use of this function starts when you save any data in the variable or get the result of any calculation and want to describe the result on the screen. No matter if you have other calculations written between the display function and the result you want to show, you can easily get the required output instantly when you call it with the help of the display function. The syntax of this function is given here:

        disp(data to display)

        Here, the data may be any string, number, variable, or anything that you have saved in the compiler and want to display now. 

        Clear Function

        We have discussed many times that we can clear the data off the screen, but you have not seen the implementation of this function. This is one of the simplest commands, and I love it because, through this, we can make room on the screen for the new calculations. The syntax is given below:

        clc

        Yes, it is as simple as shown above. You just have to write this in a new line and your screen will be cleared. One thing that must be cleared up here is that when you use this command, the data is not deleted. It is just cleared from the screen. You can see in the workspace window, all the variables and results are present just in the memory of MATLAB. 

        Maximum Function

        While dealing with the numbers, you will find this function interesting and useful because it tells you the maximum value of the data that you have provided. It may not look as important as it actually is now, but consider the case when we have a large amount of data, let's say 100, or even 1000, numbers. How will you check what the maximum number is among them? In such cases, the maximum function gives you results. Have a look at the example given below:

        I have just tried to give you the simplest example of this function by using some ordinary numbers. Once my data is stored in the variable C, I can now easily get the maximum value among all these values by using a simple command of the maximum function.

        Hence, there is no need to check each and every number all the time when I have this function. 

        Minimum Function

        Another pre-defined function of MATLAB is a minimum function that gives the exact opposite results of the case discussed above so I am not explaining it again and just showing you the implementation. 

        Whos function

        Here is the last function that I am interested to share with you. This function tells the user about the details of a particular matrix, array, or variable at the command prompt. As in the workshop window, all the values related to that variable will be displayed on the screen.

        So, it was the lecture where we defined the little but important concepts of MATLAB. The focus of this lecture was on the workshop window, and we have proved that this simple window is important to us because it shows the summary of all the variables and the saved values at just a glance. So, we hope you have learned a lot from this tutorial. Stay tuned with us for more amazing and easy tutorials.

        Variables and Arrays in MATLAB

        Hello peeps! Welcome to another tutorial on MATLAB where we are starting the code learning and its procedures in this lecture. In the previous sessions, we have seen the windows through which you can work in different ways for specific tasks. The focus of that lecture was on the figure window and editor window. Now, we are coding in these windows. You will see the implementation of these tasks in the command prompt because we are dealing with arrays as well. So, have a look at the topics that will be cleared in your mind after having the knowledge of this lecture.

        • What are the variables in MATLAB?

        • What is the relationship between the matrix and variable?

        • How to use the built-in functions of the MALTAB in command prompt?

        • Give the example of built-in functions.

        • How can you input a string message or store the results in the form string.

        We’ll try to get the example fo each case and make sure to provide you with the easiest but accurate information.

        Variables in MATLAB 

        In the prerequisites of this course, we have told you that one must have a basic knowledge of programming language. So, I am assuming that you know what actually variables are. Yet, for the sake of revision, I am discussing the concept of variables. The structural unit of the programming in MATLAB is the array. As you know, MATLAB work very closely with arrays and variables are also saved in the form of arrays in MATLAB. We have a detailed series about the matrices in MATLAB and you will see the implementation of the arrays in the command prompt window. 

        Naming the Variable in MATLAB 

        If you are confused that how MATLAB do all its task in the form of arrays, then have a look at the description of the procedure that we are giving you now. The assignment statement can be elaborated well with the help of this statement:

        var = expression;

        Consider the case when we save any value in any variable say A. The following statement is used in the command prompt.

        A= 23

        Unlike some other languages such as C++, there is no need to define the type of value in every case when declaring the variables' name in MATLAB. We have simply told MATLAB that there is a variable A with the data type int because we are saving an integer value in it. MATLAB stores this variable in the form of a one-dimensional array where the integer value 23 is saved with the name A. Now the question arises, what if we do not declare any variable name and just declare the operation on the value? This can be illustrated by the statement given below:

        sqrt(22)

        When you put the above statement in MATLAB’s command prompt, you will get the required results you were expecting. Yet, as you have not given this value any name, by default, your answers are shown with the name “ans” if you do not specify the name of the variable. All the above discussion will be cleared up with the help of the following image.

        The above discussion was made to provide the firm basis of variables and matrix in MATLAB, but now have a look deep into this procedure and check the link between these two terms. 

        Relation of Variable and Matrix

        We all know that matrices are the types of arrays that vary from one-dimensional structures to multi-dimensional according to the declaration and needs of the user. The dimensions of the matrices depend upon the number of rows and columns that we declare when introducing the matrices in MATLAB. In the case discussed above, the matrix was one-dimensional because we used a single value in the matrix, so basically, we used one row and one column only.

        The area of the memory in MATLAB, where the variable is sorted, is saved with the customer-specified name, as we have seen before in this topic, but here, it is important to notice that you can change the name of the variable at any time and the data saved in the variable will not be affected.

        While naming the arrays and, in return, we can say any variable, we have to keep in mind that the name of any variable starts with a letter. You can use special signs such as underscore after the first variable but not in the first place.

        Using Built-in Functions of MATLAB

        The real magic of MATLAB lies in its built-in functions. It seems that the designers and programmers of MATLAB have made a special effort to make the working of the mathematical functions easy and interesting, so they have made the built-in functions of the mathematical functions that, in real life, are difficult to perform and take time. A slight mistake in any step can alter the results, and it becomes difficult to recognize the mistake. Yet, with the help of built-in functions, you can easily put the values in the formulas and you are good to go. To explain this well, let me tell you about a simple type of matrix. 

        Zero Matrix in MATLAB

        A unit matrix is a type of matrix that has all the values zero in it. It is not empty, but at every place of the value, zero is saved. At the start, you must be thinking, why do we use this matrix? But these types of matrices are the basis of important functions and features of mathematics. Well, let’s design your own zero matrices of your own choice. The values obviously remain zero in every case, but the size of the zero matrices varied and, for practice, we are using the three examples.

        To apply the zero matrix at the command prompt window, we use the following formula:

         x= zeros(3)

        This will create a square zero matrix with three rows and three columns. It makes sense because we are providing MATLAB with only a single value; therefore, it uses it for the informational rows and columns.

        In the case when we want the rectangular matrix, we can use the same formula with two values inserted into it. 

        y = zeros(3,2)

        Another way to use the zeros matrix with the indirect declaration is to simply save the values that will be inserted in the zero matrix formula into a separate variable, and then simply enter that variable into the square matrix formula.

        c = [1 2; 3 4]

        z = zeros(size(c))

        In this way, I have taught you the usage of the size variable, which is another built-in function that does not look at the values saved in the matrix but just picks the size of the matrix. 

        We hope it is clear to you now. There are certain matrices mentioned in the previous session; therefore, I am not explaining more. For your practice, check and implement the table given elbow in your MATLAB command prompt.

        So, have you noticed that in our third example, we have made a matrix of size 2 by 2 and MATLAB just picked the size and used it for the formation of a zero matrix of the same size. It is one of the examples of a matrix into a matrix.

        Pre-defined Function

        Output of the function

        zeros(n)

        It creates a square zero matrix with the order nxn.

        zeros(m,n)

        It creates a zero matrix with the order mxn.

        zeros(size(arr))

        It creates a zero matrix with an order equal to the size of the array mentioned before using this function.

        eye(n)

        It creates a square identity matrix with the order nxn.

        eye(m,n)

        It creates an identity matrix with the order mxn.

        ones(m)

        It creates a square ones matrix with the order nxn.

        ones(m,n)

        It generates a ones matrix of order mxn.

        length(arr)

        It tells the length of the array.

        size(arr)

        The size of the array is examined with the help of this command. 

        Variables with the Keyboard Input in MATLAB

        Up till now, we were dealing with the variables that were related to numbers and the functions related to numerical operations. But, just like other programming languages such as C#, MATLAB also provides you with the facility to get the output in the form of a string. 

        If you want to print the message on the screen or want to have the functionality of taking input from the user, then you can do so easily by following the instructions given below:

        To print the message in the form of a string when you want to take the input from the user, you use the following command:

        user_input=input(‘message from the input’)

        Here, we have specified the general representation of the whole command, and if it is not clear to you right now, you will get it when you have a look at the example given next. This command does two tasks:

        1. It prints the exact words on the screen that are written into inverted commas. 

        2. It stops the compiler here and waits for the user to input the required values so that the compiler may use it for further calculations. 

        It is interesting to note that the user has to provide valid input all the time. MATLAB has the functionality to check the input type and it throws an error instantly. Another important point to notice is that we will write the code at the command prompt in our case. Yet, you can also write the same code in the editor window or live script, and in that case, the input stream will be shown on the command prompt presented just below the live editor. Let’s see all this discussion in action with the help of MATLAB.

        We are using the simple addition operation in the command prompt to explain the workings of the input stream. Here is the code for it.

        My_Message=input('Write two numbers to be added with the addition sign:  ')

        The user then gives the input properly and gets the results instantly.

        I have written the whole string in detail and given a long name to the variable to show you the details. Usually, the variable names are kept short because these will be used again and again in the long programs and long names can be the reason for errors because of more typing. 

        Note that, by using the command that we have mentioned before, you can not use the string as a message. Once you write the answer in the form of a string, you will get the error that there are fewer arguments in the command given above. Yet, not every time does the results in the numeric format. When you want to save the results as a string, you have to use the second argument as “s” so the compiler may know that you can also provide the input in the form of a string.

        So, you can use the input function for the string and integers and you know that integer values are just simple numbers and if you want to save the floats or other types of values, you have to save it int he form of string by using s as the second argument.

        Truss, in this lecture, we had the basic and detailed information about the variables in MALTAB. We know that MALTAB work by saving all the information in the form of arrays and therefore, at the start, we have related the variables with the arrays. After that, the implementation of the functions by the user in the MALTAB by usign different windows was discussed. Moreover, at the end, we looked at some example in which we have taken the input form the user and after that, performed the operations on it. We have taken very simple examples to make sure you are getting the best knowledge all the time. The next lecture will be related to the information given today but we will talk about some advance problems.

        Interface PCF8591 ADC/DAC Analog Digital Converter Module with Raspberry Pi 4

        Welcome back to another Python tutorial for the Raspberry Pi 4! The previous tutorial showed us how to construct a Raspberry Pi-powered cell phone with a microphone and speaker for making and receiving calls and reading text messages (SMS). To make our Raspberry Pi 4 into a fully functional smartphone, we built software in Python. As we monitored text and phone calls being sent and received between the raspberry pi and our mobile phone, we experienced no technical difficulties. But in this tutorial, you'll learn how to hook up the PCF8591 ADC/DAC module to a Raspberry Pi 4.

        Since most sensors only output their data in analog values, converting them to binary values that a microcontroller can understand is a crucial part of any integrated electronics project. A microcontroller's ability to process analog data necessitates using an analog-to-digital converter.

        Some microcontrollers, including the Arduino, MSP430, and PIC16F877A, contain an onboard analog-to-digital converter (ADC), whereas others, like the 8051 and Raspberry Pi, do not.

        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1Jumper WiresAmazonBuy Now
        2PCF8591AmazonBuy Now
        3Raspberry Pi 4AmazonBuy Now

        Required Components

        1. Raspberry-pi 4

        2. PCF8591 ADC Module

        3. 100K Pot

        4. Jumper wires

        You are expected to have a Raspberry Pi 4 with the most recent version of Raspbian OS installed on it, and that you are familiar with using a terminal program like putty to connect to the Pi via the Internet and access its file system remotely. Those unfamiliar with Raspberry Pi can learn the basics by reading the articles below.

        PCF8591 ADC/DAC Module

        Each of the ten pins on the PCF8591 module may read analog values as high as 256 on the PCF8591's digital side or vice versa. The board has a thermistor and LDR circuit. Input and output from this module are both analogs. To facilitate the I2C protocol, it has a dedicated serial clock and serial data address pins. The supply voltage ranges from 2.5 to 6V, and the stand-by current is minimal. We can further turn the module's potentiometer knob to control the input voltage. A total of three jumpers can be found on the board. Switching between the thermistor, LDR/photoresistor, and adjustable voltage access circuits is possible by connecting J4, J5, and J6. D1 and D2 are two LEDs on the board, with D1 displaying the strength of the output voltage and D2 indicating the power of the supply voltage. When the supply or output voltage is increased, the brightness of LEDs D1 and D2 are correspondingly enhanced. Potentiometers connected to the LEDs' VCC or AOUT pins also allow testing.

        Microprocessors, Arduinos, Raspberry Pis, and other digital logic circuits can interact with the physical environment thanks to Analogue-to-Digital Converters (ADCs). Many digital systems gather information about their settings by analyzing the analog signals produced by transducers such as microphones, light detectors, thermometers, and accelerometers. These signals constantly vary in value since they are derived from the physical world.

        Digital circuits use binary signals, which can only be in one of two states, "1" (HIGH) or "0" (LOW), as opposed to the infinitely variable voltage values provided by analog signals (LOW). Therefore, Analogue-to-Digital Converters (A/D) is an essential electronic circuit for translating between constantly varying analog impulses and discrete digital signals.

        To put it simply, an analog-to-digital converter (ADC) is a device that, given a single instantaneous reading of an analog voltage, generates a unique digital output code that stands in for that reading. The precision of an A/D converter determines how many binary digits, or bits, are utilized to represent the original analog voltage value.

        Analogue and Digital Signals

        By rotating the potentiometer's wiper terminal between 0 and VMAX, we may see a continuous output signal with an endless set of output values related to the wiper position. In a potentiometer, the output voltage constantly varies while the wiper is moved between fixed positions. Variations in temperature, pressure, liquid levels, and brightness are all examples of analog signals.

        A digital circuit uses a single rotary switch to control the potential divider network, taking the place of the potentiometer's wiper at each node. The output voltage, VOUT, rapidly transitions from one node to the next as the switch is turned, with each node's value representing a multiple of 1.0 volts.

        The output is guaranteed at 2-volt, 3-volt, 5 volts, etc., but NOT a 2.5-volt, 3.1-volt, or 4.6-volt output. Using a multi-position switch and more resistive components in the voltage-divider network, resulting in more discrete switching steps, would allow for generating finer output voltage levels.

        By this definition, we can see that a digital signal has discrete (step-by-step) values, while an analog signal's values change continuously over time. We are going from "LOW" to "HIGH" or "HIGH" to "LOW."

        So the question becomes how to transform an infinitely variable signal into one with discrete values or steps that a digital circuit can work with.

        Converting from Analog to Digital

        Although several commercially available analog-to-digital converter (ADC) chips exist, such as the ADC08xx family, for converting analog voltage signals to their digital equivalents, a primary ADC can be constructed out of discrete components.

        Using comparators to detect various voltage levels and output their switching signal state to an encoder is a straightforward method known as parallel encoding, flash encoding, simultaneous encoding, or multiple comparator converters.

        The equivalence output script for a given n-bit resolution is formed by a chain network of accuracy resistors and a series of comparators that are connected but equally spaced.

        As soon as an analog signal is provided to the comparator input, it is evaluated with a reference voltage, making parallel converters advantageous because of their ease of construction and lack of need for timing clocks. The following comparator circuit may be of interest.

        A Logic Comparator

        The LM339N is an analog comparator that compares the relative magnitudes of two voltage levels via its two analog inputs (one positive and one negative).

        The comparator receives two signals, one representing the input voltage (VIN) and the other representing the reference value (VREF). The comparator's digital circuits state, "1" or "0," is determined by comparing two output voltages at the input of the comparator.

        One input (VREF) receives a reference voltage, and the other input (VIN) receives the input voltage to be compared to it. Output is "OFF" by an LM339 comparator when the input power is lower than (VIN VREF) and "ON" when the input power is higher than the standard voltage (VIN > VREF). A comparator is a device to determine which of two voltages is greater.

        Using the potential divider network established by R1 and R2, we can calculate VREF. If the two resistors are identical in value (R1 = R2), then the reference voltage will be half the input power (V/2). Therefore, like with a 1-bit ADC, the output of an open-collector comparator is HIGH if VIN is lower than V/2 and LOW otherwise.

        However, by increasing the number of resistors in the voltage divider circuit, we can "divide" the voltage source by an amount equal to the ratio of the resistors' resistances. However, the number of comparators needed increases with the number of resistors in the voltage-divider network.

        For an "n"-bit binary output, where "n" is commonly between 8 and 16 bits, a 2n- 1 comparator would be needed in general. As we saw previously, the comparator utilized by the one-bit ADC to determine whether or not VIN was more significant than the V/2 voltage output was 21 minus 1, which equals 1.

        If we want to build a 2-bit ADC, we'll need 22-1 or "3" comparators since the 4-to-2-bit encoder circuitry depicted above requires four distinct voltage levels to represent the four digital values.

        Circuit for 2-bit A/D Conversion

        For each of the four potential values of the analog input of:

        A/D Conversion Output, 2-Bit

        Where X is a "don't care" statement, representing a logical 0 or 1.

        Explain how this analog-to-digital device operates. An analog-to-digital converter (A/D) must generate a faithful digital copy of the Analog input signal to be of any value. To keep things straightforward, we've assumed that VIN is somewhere between 0 and 4 volts and have adjusted VREF and the voltage divider network so that there is a 1 V drop between each resistor in this simple 2-bit Analog - to - digital example.

        A binary zero (00) is output by the encoder on pins Q0 and Q1 when the input voltage, VIN, is less than the reference voltage level, which occurs when VIN is between 0 and 1 volts (1V). Since comparator U1's reference voltage input is set to 1 volt, when VIN rises above 1 volt but is below 2 volts, U1's HIGH output is triggered. When the input changes at D1, the priority encoder, used for the 4-to-2-bit encoding, generates a binary result of "1." (01).

        Remember that the inputs of a Priority Encoder, like the TTL 74LS148, are all assigned different priority levels. The highest priority input is always used as the output of the priority encoder. So, when a higher priority input is available, lesser priority inputs are disregarded. Therefore, if there are many inputs simultaneously at logic state "1", only the input with high priority will have its output code reflected on D0 and D1.

        Thus, now that VIN is greater than 2 volts—the next reference voltage level—comparator U2 will sense the difference and output HIGH. However, when VIN is more than 3 volts, the priority encoder will output a binary "3" (11), as input D2 has a high priority than inputs D0 and D1. Each comparator outputs a HIGH or LOW state to the encoder, generating 2-bit binary data between 00 and 11 as VIN decreases or changes between every reference voltage level.

        This is great and all, but commercially available priority encoders, like the TTL, are 8-bit circuits, and if we use one of these, six of the binary numbers will go unused. A digital Ex-OR gate and a grid of signaling diodes can create a straightforward encoder circuit.

        Diode-based 2-bit ADC

        Before feeding the diodes, the results of the comparators go through an Exclusive-OR gate to be encoded. Whenever the diode is reverse biased, an external pull-down resistor is connected between the diodes' outputs and ground (0V) to maintain a LOW state and prevent the outputs from floating.

        Also, as with the main board, the value of VIN controls which comparator sends a HIGH (or LOW) signal to the exclusive-OR gates, which provide a HIGH output if either of the inputs is HIGH but not both (the corresponding Boolean is Q = A.B + A.B). The AND-OR-NAND gates of combinational logic could also be used to build these Ex-OR gates.

        The difficulty with both of these 4-to-2 converter designs is that the input analog voltage at VIN needs to vary by one full volt for the encoder to vary its output code, limiting the precision of the simple two-bit A/D converter to 1 volt. The output resolution can be improved by employing more comparators to convert to a three-bit A/D converter.

        D/A Converter, 3-Bit

        The aforementioned parallel ADC takes a voltage reading between 0 and over 3 volts as an analog input and turns it into a binary code with only 2 bits. Since there are 23 = 8 possible digital outputs from a 3-bit digital circuits system, the input analog voltage can be compared to a scale of eight voltages, each of which is one-eighth (1/8) of the voltage supply. This means that we can now measure to an accuracy of 0.5 (4/8) volts and that 23-1 comparators are needed to generate a binary code with a 3-bit resolution (from 000 (0) to 111 (7)).

        Circuit for 3-bit Analog-to-Digital Conversion

        This will provide us with a three-bit code for each of the eight potential values of the analog input of:

        The result of a Three-Bit Analog-to-Digital Converter

        An "X" may be a logic 0 or a logic 1 to indicate a "don't care" state.

        Then we can see that more comparators and power levels are required and more output binary bits when the ADC's resolution is increased.

        Therefore, an analog-to-digital converter with a 4-bit resolution needs only 15 (24-1) comparators. An eight-bit resolution requires 255 (28-1) comparators. A 10-bit resolution needs 1023 comparators, etc. Therefore, the complexity of this type of Analog-to-Digital Converter circuit increases as the number of output bits increases.

        Only if a few binary bits are needed to make a read on a display unit to represent the reference voltage of an input analog signal can a parallel or flashed A/D converter quickly be developed as part of a project due to its fast real-time conversion rate.

        As an input interface circuit component, an analog signal from sensors or transducers is converted into a digital binary code by an analog-to-digital converter. Similarly, a digital binary code can be converted into a comparable analog quantity using a Digital-to-Analog Conversion for output interfacing to operate a motor or actuator or, more often, in audio applications.

        Raspberry Pi's I2C pins

        Knowing the Raspberry Pi's I2C port pins and setting up the I2C connection in the pi 4 are the initial steps in using a PCF8591 with the Pi.

        GPIO2 and GPIO3 on the Rpi Model are utilized for I2C communication in this guide.

        Raspberry Pi I2C Configuration

        Raspberry Pi lacks I2C support by default. Therefore, it must be activated before anything else. Turn on Raspberry Pi's I2C port.

        1. First, open a terminal and enter sudo raspi-config.

        2. The RPi 4 Software Configuration Tool has opened.

        3. Third, activate the I2C by selecting Interfacing options.

          1. Restart the Pi after enabling I2C.

          Reading the PCF8591's I2C Address with a Raspberry Pi

          The Raspberry Pi has to know the I2C address of the PCF8591 IC before communication can begin. You may get the address by linking the PCF8591's SDA and SCL pins to the Raspberry Pi's own SDA and SCL jacks. The 5-volts and GND pins should be connected as well.

          You may find the address of an attached I2C device by opening a terminal and entering the following command.

          sudo i2cdetect –y 1 or sudo i2cdetect –y 0

          After locating the I2C address, the next step is constructing the circuit and setting up the required libraries to use PCF8591 and a Raspberry Pi 4.

          Connecting the PCF8591 ADC/DAC Module to the Raspberry Pi 4

          The circuit diagram to interface the PCF8591 with the Raspberry Pi is straightforward. In this example of interfacing, we'll read the analog signal from any analog inputs and display them in the Raspberry Pi terminal. We have a 100K pot to adjust the settings.

          Pi's GPIO2 and GPIO must be connected to the power supply and ground. Then, hook up GPIO3 and GPIO5 to SDA and SCL, respectively. Last but not least, link AIN0 to a 100K pot. Instead of using the Terminal to view the ADC values, a 16x2 LCD can be added.

          The A/D Conversion Python Program

          The complete code and demo video are included after this guide.

          To communicate with the I2C bus, you must first import the SMBus library and then use the time library to specify how long to wait before outputting the value.

          import smbus

          import time

          Create some variables now. The I2C bus address is stored in the first variable, and the first analog input pin's address is stored in the second variable.

          address = 0x48

          A0 = 0x40

          Next, we've invoked the library smbus's SMBus(1) function to create an object.

          bus = smbus.SMBus(1)

          The first line in the while instructs IC to take a reading from the first analog signal pin. Address information read from an Analog pin is saved as a numeric variable in the second line. Exit with the value printed.

          While True:

              bus.write_byte(address,A0)

              value = bus.read_byte(address)

              print(value)

              time.sleep(0.1)

          Finally, put the Python script in a file ending in.py and run it in the Raspberry Pi terminal with the command below.

          python filename.py

          Ensure that the I2C communication is turned on and that the pins are linked according to the diagram before running the code, or else you will get errors. It's time for the analog readings to appear in the terminal format below. The values gradually shift as you turn the pot's knob. Find out more about getting the software to work in

          Here is the full Python script.

          import smbus

          import time

          address = 0x48

          bus = smbus.SMBus(1)

          while True:

              bus.write_byte(address,A0)

              value = bus.read_byte(address)

              print(value)

              time.sleep(0.1)

          ADC's Practical Uses

          We rely heavily on electronic gadgets in today's high-tech society. The digital signal is the driving force behind these digital devices. While most numbers are represented digitally, few still use analog notation. Thus, an ADC is employed to transform analog impulses into digital ones. ADC can be used in an infinite variety of contexts. Here are only a few examples of their use:

          • The digitized voice signal is used by cell phones. The voice is first transformed to digital form using an ADC before being sent to the cell phone's transmitter.

          • Digital photos and movies shot with a camera can be viewed on any computer or mobile device thanks to an analog-to-digital converter.

          • X-rays and MRIs are just two examples of medical imaging techniques that use ADC to go from Analog to digital before further processing. Then, they're adjusted so that everyone can follow along.

          • ADC converters can also transfer music from a cassette tape to a digital format, such as a CD or a USB flash drive.

          • The Analog-to-Digital Converter (ADC) in a digital oscilloscope converts analog signals to digital ones that can then be displayed and used for other reasons.

          • The air conditioner's built-in temperature sensors allow for consistent comfort levels. The onboard controller reads the temperature and makes adjustments based on the data it receives from the ADC.

          Nowadays, practically everything has a digital counterpart, so every gadget must also include an ADC. For the simple reason that its operations require a digital domain accessible only via an analog-to-digital converter (ADC).

          Conclusion

          This piece taught us how to connect a Raspberry Pi 4 to a PCF8591 Analogue - to - digital decoder module. We have observed the output being shown as integers on our Terminal. We have also researched how the ADC generates its output signals. Here we will use OpenCV and a Raspberry Pi 4 to create a social distance detector.

          Control Project with Ladder Logic Programming

          Hey guys! hope you are all very well. Today I come to you with a new process to learn, program, and simulate for practicing ladder logic more and more. The process we are going to implement today is a very common process that could be there in many many industries which is a silo process that aims to automate the process of filling containers or bottles with a liquid. Figure 1 shows the complete scene of the process including the system components, switches, indicators, sensors, and actuators that are integrated to make the system operate. Briefly and before going into deep details, let’s state what the system does and how it operates. Well! The system automatically fills the boxes that are traveling on the conveyor which is driven by a motor. They are filled with a liquid stored in the silo shown in the middle of figure 1. The process operates continuously from the moment we hit the start button shown in the tail of the control panel on the left side of figure 1 until termination of the process is requested by pressing the stop push in the same panel. Many inputs and outputs are utilized to address the sensors, switches, push buttons, motors, and valves. So let’s get started on the project.

          Project Logic Philosophy

          As we have thought, the first step in the development of a control system is to sit with the operator or the client to get to comprehend how the system works including all details and scenarios. So the system starts by receiving the kickoff by hitting the start pushbutton. Unless there is no stop has been requested or faults, the box moves on the conveyor that is driven by a motor until it reaches the filling station which is at the silo. At that position, the box should stop for filling, and the flow of the liquid starts and goes on until the box is full. Then, it is time for the box to continue its journey to the end of the conveyor and another box commences a new trip for filling. At any time a stop is requested, the system should halt until a command to continue is presented. Operation status should be shown thanks to indicators showing the run, fill, and full status. Now, friends, that’s all the story we have gotten by sitting with the client or the operator who requested us to implement his system. have understood the requested silo operation? Well done! I know it is simple to understand but what is the next step? Yes, the next station in the project is to interpret the story narrated by our client into operation sequences and conditions and determine the list of inputs and outputs to get that project done. 

          Logic sequence

          The aims of the project we are going to implement is to implement the ladder logic program that execute the narrated logic of SILO by client. The logic can be resumed in the following sequence of operations: 

          • The batch process can be started or stopped at any point of execution 

          • Indicator lamps should be appropriately controlled to present the run, fill, and full statuses of the operation throughout the whole process.

          • All actuators should be stopped at any time a termination requested by the end user

          • The FULL lamp is switched on showing the full status of the box as long as the box at its filling position under the silo.

          • After converting the logic narrative received from the client into clear logic sequences, now the time comes to list the inputs and outputs to use to accomplish these logic sequences. In the next section, the complete list of inputs represented by sensors and switches and outputs represented by motors, valves, and light indicators. 

          Project I/Os

          Figure 2 shows the location and address of all inputs and outputs used in this project. Also, the table below lists all inputs and outputs of the project including descriptions and addresses. The control panel on the lift shows two inputs that enable an operator to start and stop the operation. Also, it shows indicators showing the status of the operation throughout the whole process. These status indicators are RUN. FILL, FULL to show the process is running, the box is filling, and when it is full. Also, it shows the motor that drives the conveyor and the proxy sensor that detects the position where the box is exactly under the silo and ready to be filled for initiating the filling process. Also, a level sensor is utilized to determine when the box is filled up to full. In addition, a valve is used to open and close the silo.

            Table 1: list of inputs and outputs of the project     

          IO

          type

          Description

          Address

          RUN

          Output

          Indicator lamp to show the running status

          Q2.2 for siemens

          O:2/02 for AB

          FILL

          Output

          An indicator lamp to show the filling process is in progress

          Q2.3 for siemens

          O:2/03 for AB

          Full 

          output

          An indicator lamp to show the full status of the box

          Q2.4 for siemens

          O:2/04 for AB

          MOTOR

          Output 

          The main motor drives the conveyor to take the boxes through their journey  

          Q2.0 for siemens

          O:2/00

          Valve

          Output

          A solenoid valve to control the silo to open or close according to the logic

          Q2.1 for siemens

          O:2/01 for AB

          Start

          input

          A pushbutton enables the operator to start the process

          I1.0 for siemens

          I:1/00 for AB

          Stop 

          Input 

          A pushbutton enables the operator to stop the process

          I1.1 for siemens

          I:1/01 for AB

          Level sensor

          input

          A level switch to detect the level of the liquid being filled into the box

          I1.4 for siemens

          I:1/04 

          Proximity switch

          Input 

          A proximity switch to sense the position of the approaching box 

          I1.3 for siemens

          I:1/03 


          Logic Flow Diagram

          Guys, this is not an essential step to accomplish the project development. But this is one of the professional ways to represent graphically the design of the logic. Figure 3 depicts the logic of the silo project graphically. You can follow paths of logic to understand how we can chart the logic flow running in our head graphically to help in writing the correct and precise code. For example, to run the conveyor motor, the start button is pressed and checked if a stop is requested, if not the run lamp indicator will be energized and latched as long as no stop is requested. Then check if a fill process is in progress. If not then the motor of the conveyor will keep running. But the question is how to know if the fill is in progress or not. On the left side of the chart, you can see if the proxy switch is on and the level switch does not show full, then the filling process is in progress. Also, if the level switch shows not full then the valve will keep open to continue filling the boxes.

          Ladder Logic Programming of the project

          Now we have just arrived at what you are waiting for! I know you want to practice programming and then simulation. Figure 4 shows the program of the silo project while the left part shows the initial state of our simulation. The first rung is to energize the run indicator when the start pushbutton is hit and no stop is requested noting the latch as we have learned. In the second rung, knowing the run is the status of the operation and no filling process is in progress, then the motor is running. In the third rung, the filling status can be determined by the proximity switch showing the boss is at the position were ready to fill and full status is not there. While the full status can be determined in the last rung when the level switch is on showing level has reached the full limit of the box and pursuing the proximity switch tells the box is on the filling spot. Before that very last rung, the valve of the silo can be determined by having the fill status on and the full status is not there yet.

          Simulating the program

          After showing you the code of the design step by step based on the received narrative from the client, deciding the IOs, and charting the logic of the program. Now it is time to simulate the program to make sure the design and the code are correct. Figure 5 shows the running status of the operation. By hitting the start push button, the conveyor move by the driving motor and takes the box to the filling station. Guys, notice please the run indication lamp is on in the code highlighted in yellow and on the control panel on the right as well. Also, notice the motor is spinning.

          Figure 6 shows the box stopped for filling at the silo thanks to the proximity switch. Notice the run lamp is on and the motor is de-energized for letting the box fill. Also, notice the fill status is on and the lamp indicator is energized. Also, see the valve is open to let the liquid fills the box.

          Figure 7 shows when the box comes to be full. You can see the run operation status is still on. And the full status is indicated by the full lamp. Also, once the box is full, the motor starts spinning again taking the filled box out from the line to let other incoming boxes come.

          And finally, after filling to full, the filled boxes keep going as shown in figure 8 to the end of the conveyor. You can see the run status is still energized and the motor is spinning. After that, the cycle will continuously be repeated until the stop is requested. So let us see the termination of the process.   

          on the other hand, when the stop push button is pressed requesting termination of the process, the motor stops spinning and the whole process stopped until a proceeding instruction is issued by hitting start again. Guys, that is very common to enable the machine operator to stop for any emergence or do any repainting before baking to work again 

          What is next???

          First of all, I would like to thank you all for continue following the tutorial till this very point. As you see we are taking projects from real life. It might be small projects or processes but that is what you will see in real industry life. So next time we select one of the common processes in the real life and do the same design, coding, and without question practicing using our simulator. So please be ready, study hard, and let’s meet for our next project.

          MATLAB Windows | Figure Window | Editor Window

          Hello learners, Welcome to another tutorial on MATLAB. In the previous tutorial, we learned a lot about MATLAB's command window, saw some exciting commands related to the system, and found guidance from the pre-defined data. In this lecture, you will learn a great deal about the other two types of windows we defined in the earlier sessions. Let me discuss the points that will be discussed today. 

          • What is a Figure window?

          • How to get started with the figure window?

          • How can you change the background colour of the figure window?

          • What are some functions of the figure window?

          • Give a brief introduction to the editor window.

          • What is the live script?

          • How to run code on the live script?

          • What is the difference between the run all and run section options in MATLAB?

          We shall discuss all these questions during our session you are going to learn a lot of things because we have precise and interesting data for your learning and practice related to MALTAB.

          Figure Window

          MATLAB provides us with various functionalities related to the mathematical operations and working of different theorems in the best way. When talking about graphics, we come to know that they provide the perfect way to facilitate the user in the best way. So, it provides the user with a high-quality graphic window that shows the results of different calculations in a pictorial way. This will be clear when you see the implementation of different commands while designing your own figure window in the command prompt. 

          Getting Started with the Figure Window

          It is amazing to know that you can easily label your own figure window according to your task by using some simple commands. So, have a look at the following steps:

          Open your MATLAB software.

          Go to the command window.

          The syntax for creating a new figure window is as follows:

          figure (‘Name’, ‘Value’)

          Where the keyword “Name” tells MATLAB that you want to name your figure window according to your will, and the value shows the value that you want to store in place of the window’s name.

          Now, write the following command there.

          figure (‘Name’, ‘My Figure Window’)

          You will observe that it will create a square window that is labelled with your required title, and it will appear instantly when you finish your command and press enter.

          Making The Graph in Your Figure WIndow

          As we have been discussing since the beginning, the figure window has made the representation of different graphs super easy. You just have to put in the values and the graph with the accurate values will appear on the screen. If you want to do so, check out the following way:

          Go to your Command window and provide the values of the bar to MATLAB. In our case, we are storing these values in a variable named “Y”. Examine that all the values are stored in a square bracket. 

          Y = [1,44,66,8,33,89,34,4,22]

          In the next line, you have to write the function of the window's formation. Write the next line in your code.  We are making a new window because we wanted to teach you another thing related to the figure window. Write the next line in your code.

          figure ('Name', 'My Figure Window', 'NumberTitle', 'off')

          With the help of this command, MATLAB will surely create a window for you not only with the same title but also without any additional title other than your written statement, as we have observed in the previous case (title with the figure number).  It seems like an ordinary feature of the figure window, but most of the time, you are not going to use these options.

          In the end, we are using the pre-defined function of MATLAB named bar that creates the bar graph of the values stored in your variable Y.

          bar (Y)

          You will see, a nice and interesting figure window with all the data that was fed by you.

          Background Colors in Figure WIndow

          During this discussion, when I said that you are also going to design your own window, I meant that you can change the background colours and the data of the figure window made by you. If you want to do so, then you just have to make little changes in the command for the formation of your window.

          figure ('Name', 'My Figure Window', 'NumberTitle', 'off', 'Color', 'r');

          Here, the colour function is specified in red by using the keyword “r”. There are different keywords for different colours. Check the same command by using ‘b’ instead of ‘r’ and you will get the blue screen. 

          Functions in Figure Window

          Let me tell you another command through which you will get some points scattered on the screen with the blue background. Just write the following command on the command prompt.

          figure ('Name', 'My Figure Window', 'NumberTitle', 'off', 'Color', 'b')scatter((1:23),(rand(1,23));

          Here we have used two different functions that may be new to you. 

          The scatter function gives the MATLAB some values, say x and y, where x shows the starting point and y shows the ending point, in between which the distance between the points shown in the figure is taken by MATLAB. 

          On the other hand, the random function chooses one of the random numbers between the limits provided by us. After that, it shows the number of dots accordingly. Both of these are important functions, and one thing that must be kept in mind is that the limits of both these functions must be equal. Otherwise, MATLAB will make the error that the dimension of these functions must be the same. You can pick any number for these limits. 

          Editor Window in MATLAB

          The MATLAB editor is a fantastic window because most of the commands and functions that are related to different functions are done with the help of pre-defined commands and functions. We discussed the basic introduction of the editor window in our previous lecture. This time, we are discussing it deeply. MATLAB provides two versions of the editor window:

          1. Editor Window

          2. Live Editor

          To use the editor window, simply follow the steps that we are specifying here:

          • Open your MATLAB software.

          • Go to the command window.

          • Write “Edit” in the command window. 

          It will open a new screen where you can create multiple windows, and the screen now looks like this:

          As soon as you try to run this file, a window will appear that will require the information of the file where this code will be saved in your MATLAB folder. So, I suggest naming it meaningful so that any time you need the code, you simply click on the saved file, and your saved code will be shown as expected.

          The command window now lies below the editor window, and you can use it for several operations. The editor window is also referred to as the script window, and at this point, we want to work on the other type of editor, which is the live window. 

          • Go to the main menu of your screen and choose the live editor there. You will be directed to the new window.

          Let’s start by writing the code in this window. 

          • For now, I am going to show you the result of some coding and, hopefully, you will love it. 

          • Copy this code from here and paste it into the editor window. 

          For the compilation of this code, t=2:0.1:1

          x=[1 2 4 7]

          h=[4 7 8 1]

          a=xcorr(x,h)

          subplot(2,1,1)

          stem(a)

          title('Correlation')

          xlabel('Time / The Engineering Projects’)

          ylabel('Amplitude')

          grid on;

          • You have to press f5 for the compilation of this code. The advantage of this window is that the results can be seen instantly without the need to store the code in a file. 

          So, you will get the result as shown in the picture.

          For now, I am not going to elaborate on the code and the concepts, but for now, you just have to get an idea of how the live window is used. 

          The Difference in MATLAB Editor Windows

          The difference between these two types of editor windows is given below:

          Editor Window

          Live WIndow

          The code has to be saved in a separate file to see the results.

          There is no restriction on saving the results into a separate file. 

          The results are shown in a separate figure window if applicable. 

          The results can be seen instantly when we run the program by pressing f5 in a side window. 

          We can change the position and size of the figure window and can minimize it if required. 

          The results can be shown at the side of the code or just below it. 

          It is a simple window resembling the command prompt window with a white background. 

          It is a relatively stylish window with a grey background. 

          The compilation process shows the results all at once when we run the program. 

          An indicator at each line tells us the position of the current compilation line.

          Hence, both of them have the same type of work, but they are different with respect to some features that are used according to the skills and requirements of the user. 

          Live Script Options in MATLAB

          You can find different types of operations related to the live editor or simple editor window that you will use every time no matter what type of function it is performing. These options appear when you hover over the options present on the upper side of the screen just above the live editor window.

          For different operations on MATLAB, you can use all these windows, but for now, our concentration is on the live editor window. It gives us the independence to use the new, open and save file options. You are not new to these functions, so I am not going to elaborate, but the things that must be clarified here are the workings of the run all and run section options. 

          These buttons have the same function, but the way they work is a bit different. The "Run all" button obviously runs the code at once, but when we talk about the "Run section" button, it is somehow different from the first case. 

          Run Section in MATLAB

          The "Run Section" button gives us the independence to run the codes in different parts. It was designed to give ease to the coder because in most of the codes, we have long and confusing codes, and it feels like a gift from the designers because many times, you do not know which part of the code is not working or showing the error. So, it becomes super easy to run the code in different sections to check the results separately and detect the error.

          Hence, it was an important lecture where we found interesting information about the windows of MATLAB. Keep in mind, MATLAB has a gigantic amount of information about different types of functions used in math, and therefore, it provides sections and different windows for the usage and working of different tasks related to the academic and professional world in the best way. If we talk about the commands and functions along with all the features it provides with the help of these manus, then the lecture will become very lengthy. For now, your homework is to check the manus by applying different options to your code. 

          MATLAB has amazing windows for its work, and the figure window is one of the most important because it allows you to have the results in the form of graphs. By the same token, the editor window is the one that is used to write code and get the result in different ways. We have two types of windows to write code that is called editor windows and live scripts. Both of them seem alike but have different features, and programmers use them according to their needs.

          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