We are here with yet another set of interview questions. For all budding data science and machine learning professionals, Matlab is an essential area to focus on. We have compiled a list of the most frequently asked questions for Matlab interviews along with their answers to help you prepare better. Read on to find out what’s in store.

**Q 1. What is MATLAB ?**

**Ans. **MATLAB is an acronym for MATrix LABoratory. It is an open-source software/API which was initially developed for the mathematical calculations including matrix operations. The latest version of the software can perform on various types of complex calculations such as data analysis and visualization, scientific and engineering graphics etc. It’s prime features also include simulation and modelling.

**Q 2. How to install MATLAB ?**

**Ans. **For installing the latest version of MATLAB i.e., MATLAB R2020b : –

Prerequisites (for Windows) :

- A PC or desktop computer with Windows 10 or at-least Windows 7.
- Any Intel or AMD x86-64 processor (for the sake of your pc).
- A minimum 4 GB RAM but 8 GB is recommended.
- SSD is recommended, but 3.5 GB HDD space for MATLAB only, 5-8 GB for a typical installation.
- Graphic card is not required.

Prerequisites (for Mac) :

- macOS Big Sur (11) or macOS Catalina (10.15) or macOS Mojave (10.14).
- Any intel processor x86-64 processor.
- A minimum 3.4 HDD space is required, but for a full installation space of 29 GB is required.
- A minimum 4 GB RAM but 8 GB is recommended.
- Graphic card is not required.

Prerequisites (for Linux) :

- Ubuntu versions after the one of 16.04 LTS, Debian 9 and newer versions, Red Hat Enterprise Linux 7 and newer, SUSE Linux Enterprise Desktop 12 and newer and SUSE Linux Enterprise Server 12 and newer.
- Any Intel or AMD x86-64 processor.
- 3.3 GB of HDD space for MATLAB only, 5-8 GB for a typical installation. But an SSD is recommended.
- A full installation of all MathWorks products may take up to 28 GB of disk space.
- A minimum 4 GB RAM but 8 GB is recommended.
- Graphic card is not required.

Installation is same for all OS. You can download the software from any safe website such as its source mathworks.com , or sourceforge.net .** **Simply open the browser and navigate to the URL given above and download the software.

But be aware of the fact that MATLAB is such a huge software with its latest update of more than 20 GB, it will not be installed overnight or in a single attempt. So, it is recommended to use any internet download manager to install it on a multi-day attempt.

**Q 3. How to plot a graph in MATLAB ?**

**Ans. **For any two points x and y with some values given, a function called plot (x, y) is used to plot a graph in MATLAB.

** Syntax : **x : [value of array];

y : [value of array];

plot(x, y)

**Q 4. How to call a function in MATLAB ?**

**Ans. **A function in MATLAB can be called using the name you give to the function, but first it needs to be written in the New Script tab under the File Tab. You can simply call the function by writing the function’s name in the code area.

>> function_name (in the work area)

**Q 5. What is MATLAB used for ?**

**Ans. **MATLAB language is a high-level matrix language. It has control structures, functions, data structures, input/ output and OOP features. MATLAB API allows to author C and FORTRAN programs to interact with MATLAB. It is used for various industry level designing processes and for running the control systems, automations of different types of machines, by defining a particular set of codes for an object.

**Q 6. How to run MATLAB code ?**

**Ans. **NOTE:- Before running any code, make sure you save the respective code, so that your progress doesn’t fly away. Any code can run in MATLAB, once it’s saved, by using the Save and Run button in the home tab of MATLAB, or you can simply use the F5 key on your keyboard.

**Q 7. How to read image in MATLAB from a folder ?**

**Ans. **A syntax to read image from any folder is given as :-

D = ‘directory where the files are saved’;

S = dir(fullfile(D,’name*.jpg’)); % pattern to match filenames.

for k = 1:numel(S)

F = fullfile(D,S(k).name);

I = imread(F);

imshow(I)

S(k).data = I; % optional, save data.

end

**Q 8. How to write function in MATLAB ?**

**Ans. **A function can be written in MATLAB using the New Script option under the File tab.

*Steps to write a function :-*

- Click on the file tab.
- Click on the New Script option.
- A new box will appear wherein you will get a syntax given as

function [y1, …,yN] = function_name(x1, …,xM)

end

function [y1, …,yN] = myfun(x1, …,xM) declares a function named function_name that accepts inputs x1, …,xM and returns outputs y1, …,yN.

Here you can write a function and save it in the folder.

**Q 9. How to use for loop in MATLAB ?**

**Ans. **A for loop is used to repeat a certain set of instruction a fixed number of times.

The syntax of for loop is :-

for index = values

statements

end

for index = values, statements, end executes a group of statements in a loop for a specified number of times.

**Q 10. How to solve differential equations in MATLAB ?**

**Ans. **Any differential equation can be solved following a set of instructions and a proper syntax. But for more accuracy, we use some solvers, casually known as ODE solvers in general used for ordinary differential equations. Some of the commonly used ODE solvers are:- ode23, ode45, ode15s and ode23s.

*Syntax to solve differential equations in MATLAB :-*

- Create a function in an m-file to define the right-hand side of the equation to be solved.
- Determine the interval length for independent variable tspan.
- Enter the initial conditions as n
_{0}. - Call the solver to obtain the solution by typing the following command:-

_{0})

- The left-hand side of the command is the output argument containing two vectors. Other solvers too use the similar syntax.

After saving this script, we can call the function by its name or as the saved script name with given some initial conditions to get the answers.

**Q 11. How to read csv file in MATLAB ?**

**Ans. **CSV stands for Comma-Separated Values. A command called csvread is generally used to read the csv files, but is not actually preferred.

** Syntax : **M = csvread(filename)

The newer version of MATLAB instead recommends readmatrix to read such type of files.

** Syntax :** A = readmatrix(filename)

**Q 12. What is MATLAB software ?**

**Ans. **MATLAB is a high-performance language for technical computing. Computation, visualization and programming are integrated with MATLAB, in easy-to-use environment. It helps the user in development of algorithms, complex calculations, simulation, modelling and prototyping of data.

**Q 13. How to comment in MATLAB ?**

**Ans. **Comments in MATLAB can be inserted in between the codes. The syntax for comment goes like this:-

“ % your comment goes here. ”

**Q 14. How to open SIMULINK in MATLAB ?**

**Ans. **SIMULINK can be easily accessed in MATLAB by the use of Home tab. Simply go on the Home tab and click Simulink.

**Q 15. How to implement neural network in MATLAB ?**

**Ans. **A neural network is an adaptive system that learns by using interconnected nodes or neurons in a layered structure that resembles a human brain. A neural network can learn from data, so it can be trained to recognize patterns, classify data, and forecast future events.

It breaks down the input into layers of abstraction. It can be trained using many examples to recognize patterns in speech or images, for example, just as the human brain does. Its behaviour is defined by the way its individual elements are connected and by the strength, or weights, of those connections. With just a few lines of code, MATLAB lets you develop neural networks.

The work flow for the general neural network design process has seven primary steps :-

- Collect data
- Create the network
- Configure the network
- Initialize the weights and biases
- Train the network
- Validate the network (post-training analysis)
- Use the network

MATLAB and Deep Learning Toolbox provide command-line functions and apps for creating, training, and simulating shallow neural networks. The apps make it easy to develop neural networks for tasks such as classification, regression (including time-series regression), and clustering. After creating your networks in these tools, you can automatically generate MATLAB code to capture your work and automate tasks.

**Q 16. How to write for loop in MATLAB ?**

**Ans. **Here is presented an example on ‘for loop’ in MATLAB :-

A = [3 6 9 4 1];

for i = 1:length(A)

disp(A(i))

end

As discussed earlier, a for loop is used is often used to assign to or access array elements iteratively.

**Q 17. How to create matrix in MATLAB ?**

**Ans. **To create an array with n number of elements in m number of rows, separate the elements with either a space or comma. For example, to create a matrix A of order 3 X 3, we write it as:-

A = [ 21 92 43, 45 67 54, 72 88 91 ]

The result to which will be represented as :-

A = 3 X 3

21 92 43

45 67 54

72 88 91

**Q 18. How to create GUI in MATLAB ?**

**Ans. ***Steps to create a GUI :-*

- Start GUIDE by typing guide at the MATLAB prompt.
- In the GUIDE Quick Start dialog box, select the Blank GUI (Default) template, and then click OK.
- Display the names of the components in the component palette:

- Select
**File**>**Preferences**>**GUIDE**. - Select
**Show names in component palette**. - Click
**OK**.

Following the steps, you can start to create a GUI in MATLAB.

**Q 19. How to use SIMULINK in MATLAB ?**

**Ans. **SIMULINK in MATLAB is used to create a model for some process, for example, a simplified motion of a car, or any control system process. When you use MATLAB ® and Simulink ® together, you combine textual and graphical programming to design your system in a simulation environment. SIMULINK can be accessed in MATLAB from the Home tab itself. SIMULINK is basically a graphical block diagramming tool with customizable set of block libraries. When opened, Simulink opens with the Library Browser. The Library Browser is used for building simulation models.

On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane. To create a new model, click the New button on the Library Browser’s toolbar. This opens a new untitled model window. A Simulink model is a block diagram.

Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window. Alternately, you can copy the model elements and paste them into the model window. Here you can choose any models based on your choice of developing any project.

**Q 20. How to stop a program in MATLAB ?**

**Ans. **You can simply use the quit command to stop a program in MATLAB or you can use the desktop shortcut such as Ctrl + C.

**Q 21. How to plot a circle in MATLAB ?**

**Ans. **You can use this given example, or rather say syntax to plot a circle in MATLAB.

Here is a MATLAB function that plots a circle with radius ‘r’ and locates the centre at the coordinates ‘x’ and ‘y’ :-

function h = circle(x, y, r)

hold on

th = 0 : pi/50 : 2 * pi;

xunit = r * cos(th) + x;

yunit = r * sin(th) + y;

h = plot(xunit, yunit);

hold off

And you can run the code in the work space by typing the word ‘circle’ and the input conditions.

**Q 22. How to interface ARDUINO in MATLAB ? **

**Ans. ***Steps to interface ARDUINO with MATALB :- *

- Start MATLAB and click the Add-Ons drop down menu. In the drop-down menu click Get Hardware Support Packages. It will start the package installer window.
- Select Install from Internet and click Next.
- In the next window you will see all the available packages for MATLAB and Simulink. Select the Arduino package, then check all the packages displayed and click Next to continue installation.
- Next, the installer will ask you to log in to your MathWorks account. If you don’t have an account, you can create one during installation. Accept the license agreement on the next screen and continue to download the packages. Now you have to wait for MATLAB to download and install all the required packages.

*How to check if the connection is successful :-*

Once the packages are installed, connect your Arduino board to your PC and type the following command in MATLAB command window,

>> a = arduino()

MATLAB will then attempt to communicate with your board. If successful, MATLAB will display the properties of the Arduino board connected to your PC.

**Q 23. How to import data from EXCEL in MATLAB ?**

**Ans. **You can do this by clicking the Import Data icon under the Home tab and navigating to the Excel file you that want to import. Its just a simple step.

**Q 24. How to remove background from image in MATLAB ?**

**Ans. ***These are some steps to remove background image in MATLAB ***using color-based segmentation using K – means Clustering ***:- *

**Read the image. It follows the given syntax :-**

he = imread(‘hestain.png’);

imshow(he), title(‘H&E image’);

text(size(he,2),size(he,1)+15,…

‘Image courtesy of Alan Partin, Johns Hopkins University’, …

‘FontSize’, 7, ‘HorizontalAlignment’, ‘right’ );

Where imread is the function to read the image named hestain.png.

**Convert the image from RGB colour space to L*a*b*colour space**

The L*a*b* color space is derived from the CIE XYZ tristimulus values. The L*a*b* space consists of a luminosity layer ‘ L* ‘, chromaticity-layer ‘ a* ‘ indicating where color falls along the red-green axis, and chromaticity-layer ‘ b* ‘ indicating where the color falls along the blue-yellow axis. All of the color information is in the ‘ a* ‘ and ‘ b* ‘ layers.

It follows the syntax :-

lab he = rgb2lab(he);

**Classify the colors in ‘a*b*’ Space Using K-Means Clustering.**

Clustering is a way to separate groups of objects. K-means clustering treats each object as having a location in space. It finds partitions such that objects within each cluster are as close to each other as possible, and as far from objects in other clusters as possible. K-means clustering requires that you specify the number of clusters to be partitioned and a distance metric to quantify how close two objects are to each other.

ab = lab_he(: , : , 2:3);

ab = im2single(ab);

nColors = 3;

% repeat the clustering 3 times to avoid local minima

pixel_labels = imsegkmeans( ab, nColors, ‘NumAttempts’, 3);

For every object in your input, imsegkmeans returns an index, or a label, corresponding to a cluster. Label every pixel in the image with its pixel label.

**Q 25. How to implement svm in MATLAB ?**

**Ans. **A support vector machine (SVM) is a supervised learning algorithm used for many classification and regression problems , including signal processing medical applications, natural language processing, and speech and image recognition. The main goal of the SVM algorithm is to separate data points of one class from those of another class to the best degree possible.

Support vectors refer to a subset of the training observations that identify the location of the separating hyperplane. The standard SVM algorithm is formulated for binary classification problems, and multiclass problems are typically reduced to a series of binary ones. You can use a support vector machine (SVM) when your data has exactly two classes.

**Q 26. How to add toolbox in MATLAB ?**

**Ans. **To create a toolbox installation file :-

- In the Environment section of the Home tab, select Package Toolbox from the Add-Ons menu.
- In the Package a Toolbox dialog box, click the ‘plus’ button and select your toolbox folder. It is good practice to create the toolbox package from the folder level above your toolbox folder. The .mltbx toolbox file contains information about the path settings for your toolbox files and folders. By default, any of the included folders and files that are on your path when you create the toolbox appear on their paths after the end users install the toolbox.
- In the dialog box, add the information about your toolbox such as, ToolBox name, version, Author name, email and Company, ToolBox image, its summary and description.
- To save your toolbox, click Package at the top of the Package a Toolbox dialog box. Packaging your toolbox generates a .mltbx file in your current MATLAB folder.

**Q 27. How to add path in MATLAB ?**

**Ans. **A MATLAB function named addpath is used to add a path in MATLAB.

The syntax for addpath goes as :-

addpath( ‘directory’ )

or

addpath( ‘dir’, ‘dir2’, ‘dir3’ …)

Here addpath( ‘directory’ ) prepends the specified directory to the current MATLAB search path, that is, it adds them to the top of the path. Use the full pathname for directory.

addpath( ‘dir’, ‘dir2’, ‘dir3’ …) prepends all the specified directories to the path. Use the full pathname for each dir.

As an alternative to the addpath function, use the Set Path dialog box. To open it, select Set Path from the File menu in the MATLAB desktop.

We use the Set Path dialog box for the following :-

- Viewing the Search Path
- Adding Directories to the Search Path
- Moving Directories Within the Search Path
- Removing Directories from the Search Path
- Restoring the Default Search Path
- Reverting to the Previous Path
- Saving Settings to the Path
- Editing pathdef.m

**Q 28. How to declare array in MATLAB ?**

**Ans. **An array can be declared in MATLAB using the following syntax :

A = [1 2 3 4 5]

It creates an array of 1X5.

Or it can be declared in the following syntax :

N=[1,2,3,4,5]

It also creates an array of same 1X5 dimension.

**Q 29. How to calculate classification accuracy in MATLAB ?**

**Ans. **Here’s one approach we may try:

% output= evalfis( fis, input);

pred = round(output);

acc_count = nnz( pred==input);

acc = acc_count/length(input);

Here we are considering round values of the fuzzy system as the predictions obtained and then counting the number of correct predictions over the total number of inputs.

**Q 30. How to generate sine wave in MATLAB ?**

**Ans. **A program to generate sine wave in MATLAB is given below :-

t = 0:0.01:2;

w = 5;

a = 4;

st = a*sin(w*t);

plot(t, st);

Using this program and altering the values of ‘t’, ‘w’ and ‘a’, we can further generate longer sine waves.

**Q 31. How to read audio file in MATLAB ?**

**Ans. **Here is the syntax to read audio files in MATLAB :-

Here it reads data from the file named filename, and returns sampled data, y, and a sample rate for that data, Fs.

**Q 32. How to resize an image in MATLAB ?**

**Ans. **Image resize in MATLAB can be done by using the following syntax :-

J = imresize( I, scale)

The above given syntax returns image J that is scale times the size of I. The input image I can be a grayscale, RGB, binary, or categorical image.

**Q 33. How to comment multiple lines in MATLAB ?**

**Ans. **Multiple line comment in MATLAB can be done using the syntax :-

%{

Comments go here

%}

**Q 34. What is the MATLAB working environment ?**

**Ans. **MATLAB working environment has various tools to work with MATLAB. It has facilities to manage variables. MATLAB supports export and import data across applications. Certain tools are available to develop and manage MATLAB files. Debugging and profiling of MATLAB applications are more flexible with MATLAB. It is the blank space in between the functions and command history box where we can write the codes.

**Q 35. Explain how polynomials can be expressed in MATLAB ?**

**Ans. **There are a number of ways in which a polynomial function can be expressed in MATLAB. Polynomials are equations of a single variable with nonnegative integer exponents. MATLAB represents polynomials with numeric vectors containing the polynomial coefficients ordered by descending power. For example, [1 -4 4] corresponds to x^{2} – 4x + 4. Some of the functions are :-

Poly, polyeig, polyfit, residue, roots, polyval etc.

**Q 36. Explain handle graphics in MATLAB ?**

**Ans. **Handle Graphics is a subsystem of MATLAB that handles graphics. It has high level commands for 2D and 3D data visualization. Image processing, animation and presentation graphics can be generated using Handle Graphics. Low level commands allow customizing the graphics appearances. Handle Graphics allows to build customized Graphics User Interfaces.

**Q 37. What are the types of loops that MATLAB provides ?**

**Ans. **MATLAB provides three types of loops, just like any other programming language, which are :-

- For loop
- While loop
- Nested loops (if else, elif etc) .

**Q 38. What are 3D-Visualization elements in MATLAB ?**

**Ans. **3D-visualization elements lets MATLAB deal with the 3D graphics. These are some of the 3D-visualization elements in MATLAB :-

**Surface and Mesh plots –**Includes plot matrices and colour maps.**Lightening –**Used for adding and controlling scene lightening.**Transparency –**Used to specify object transparency.**Volume visualization –**Used for volume data grid.

**Q 39. What are memory management functions in MATLAB ?**

**Ans. **There are basically five types of memory management functions in MATLAB, which are:-

1. clear – Removes variables from memory.

2. pack – Saves the existing variables to disk, and then reloads them contiguously.

3. save – Selectively persists variables to disk.

4. load – Reloads a data file saved with the save function.

5. quit – Exits MATLAB and returns all allocated memory to the system.

**Q 40. What do you mean by M-file in MATLAB ?**

**Ans. **An M file is a text file used by MATLAB .It can store a script, class, or an individual function in the MATLAB language. M files are used for executing algorithms, plotting graphs, and performing other mathematical operations. It is the basic type of files that MATLAB have. The extension for m file is .m . Any file with the extension .m is a m-file.

**Q 41. What are MEX files ?**

**Ans. **A MEX file is a function, created in MATLAB, that calls a C/C++ program or a Fortran subroutine. A MEX function behaves just like a MATLAB script or function.

The MEX file contains only one function or subroutine. The calling syntax depends on the input and output arguments defined by the MEX function. The MEX file must be on your MATLAB path.

**Q 42. What are standard toolboxes present in MATLAB? How can they be accessed?**

**Ans. **There are a variety of toolboxes present in MATLAB, some of which are:-

- Optimization
- Neural Networks
- Partial Differential Equations
- Image processing
- Statistics
- Wavelets
- Control systems

And many more…

To access these toolboxes, simply go to the MATLAB start menu, after which choose the Toolboxes sub menu, then choose the Toolbox which we want to use.

**Q 43. What is Xmath ?**

**Ans. **Xmath is an interactive scripting and graphics environment for X-window workstations. It can script languages with OOP features. It is a debugging tool with GUI features.

**Q 44. Can we run MATLAB without graphics ?**

**Ans. **The answer is YES. We can run MATLAB without graphics too, since it is a GUI. Also, at times, we can run the script codes without displaying the graphs.

**Q 45. What is a P-code ?**

**Ans. **P-code is a way to safe-key your source code such that others do not have any access to the source code of any of your projects. The original extension for a MATLAB file is .m but for a p-code applied file is .p . A P-code file behaves the same as the MATLAB source. When MATLAB P-codes a file, the file is obfuscated and not encrypted.

**Q 46. What is Stress Analysis in MATLAB ?**

**Ans. **Stress Analysis or Finite Element Analysis is a computational method for predicting how any object will react to the real-world forces, heat, vibrations etc. We are well aware of the fact that MATLAB is a multidimensional software which finds its application in various disciples of engineering and for example, mechanical engineering makes use of stress analysis to design automotive et al.

Hope these questions have helped you to understand the core concepts of Matlab better and prepare for the interview. For more learning content on Data Science and Machine visit **Great Learning Academy** where you will find various courses for professionals for free.