## Important Viva Questions of MatLab for Electrical Engineering

Hi guys,
We have collected some important questions of matlab (Matrix laboratory) for 3rd sem Electrical Engineering. Just check it out or download these questions in PDF from here :

Set-1:

## “The input                      w as too complicated or too big for MATLAB to parse” when such error occurs and how this error can be prevented?

This kind of error occurs when a program file includes thousands of variables or functions, thousands of statements, or hundreds of language keyword pairs (e.g., if-else, or try-catch).

It can be overcome by following ways:
• Split large script files into smaller ones, having the first file call the second if necessary.
• Take larger chunks of program code and make separate functions (or sub functions and nested functions) of them.
• If the functions or expressions seem overly complicated, make smaller and simpler functions or expressions of them. Simpler functions are also more likely to be made into utility functions that can be shared with others.

## Why the conversion of data types of variables is not suggested in matlab? How the conversion can be done, if required?

If the class or array of a variable is changed it will have the following negative effects:
• It slows down the process.
• It takes extra time
• It has a negative impact on the performance
So to avoid the above negative effects it is always advisable to create a new variable.

X which is a double type variable can be changed char type by the following code:

X = 56;
X = 'A'; % X changed from type double to char

## How vectorization is helpful in MATLAB?

Firstly vectorization helps in the conversion of vector or matrix operations from “for” and while” loops, secondly its algo speeds up the code as it is really short.

For Example:
One way to compute the sine of 1001 values ranging from 0 to 10:
i = 0;
for t = 0:.01:10
i = i + 1;
y (i) = sin (t);
end

A vectorized version of the same code is
t = 0:.01:10;
y = sin(t);

The second example executes much faster than the first

## Which Graphic sytem is used in MATLAB? Explain it.

The graphic system which is used in Matlab is known as handle graphics. It has few high level and low level commands.
• High level commands performs data visualization, image processing, and animation for two dimensional and three dimensional presentation graphics.
• Full customization of the appearance of graphics and building of complete Graphical user interfaces on is done by low level commands in MATLAB applications.

## Describe the various system parts of MATLAB

Various system parts of MATLAB include:

1. The MATLAB language: consists of high level array language.
2. The MATLAB working environment: set of tools and facilities that you work with as matlab user.
3. Handle Graphics: It includes high level and low level commands.
4. The MATLAB mathematical function library:It’s a collection of computational algorithms.
5. The MATLAB Application Program Interface (API): It’s a library which allows to write C and Fortran programs.

## List down the things for which MATLAB can be used

Matlab can be used for following things:
• Performing very simple calculations
• Plotting mathematical relationships in two dimensional and three dimensional
• For operations of matrix
• For creating script files which is a type of programming
• For manipulating equations
• Advanced visualization, animation and GUI interface tools

## What are the functions used to read text files from a certain format in Matlab?

Following functions can be used to read a text file:

DLMREAD: It allows you to read files with fields delimited by any character.
TEXTREAD: It allows you to skip lines at the beginning, ignore certain comment lines, read text as well as numbers, and more.
myfile.txt: It is for the file which has nothing but numbers separated by space, and has a constant number of columns through the entire file. Other functions are FOPEN, FREAD, FSCANF, FGETL, FSEEK and FCLOSE.

## What do you mean by M-file in matlab?

M-files are nothing but just a plain ASCII text that is interpreted at run time. We can say these are the subprograms stored in text files with .m extensions and are called M-files. M-files are used for most of the MATLAB development, and for platform independence and maintainability. It is parsed once and "just-in-time" compiled, but it is also transparent to the user. Few e.g. of M-file functions are Derivative functions (derivs.m), Definite Integral Function (defint.m) etc.

## What is a P-code?

P-code files are purposely obscured; they offer a secure means of distribution outside of your organization. Pcode is a preparsed and encoded version of the M-file. It saves on the load time of the function. This is most likely not an issue except for very large M-files, since most are parsed only once anyway. Pcode also lets you hide the source code from others. There is no way to convert Pcode back to the M-file source. Pcode is platform independent.

## What are MEX files?

MEX files are basically native C or C++ files that are dynamically linked directly into the MATLAB application at runtime. It allows to use C, C++ and fortran programs in MATLAB. They must be compiled for each hardware architecture on which they are to be run. MEX files have the potential to crash the MATLAB application, but rather large speed gains are possible, depending on the algorithm.

## How the source code can be protected in Matlab?

By default the code is saved in (.m) extension, which is secured but if the user wants it to be stored in a more secured way then he can try the following methods:

1. Make it as P-code : Convert some or all of your source code files to a content-obscured form called a P-code file (from its .p file extension), and distribute your application code in this format.
2. Compile into binary format : Compile your source code files using the MATLAB Compiler to produce a standalone application. Distribute the latter to end users of your application.

## What is Interpolation and extrapolation in Matlab? What are its different types?

Interpolation can be defined as taking out function values between different data points in an array whereas finding function values beyond the endpoints in an array is called extrapolation. Commonly both can be done by using nearby function values to define a polynomial approximation to the function that is good over a small region.

There are two types of Interpolation and Extrapolation:
• Linear Interpolation and Extrapolation

## What is fminsearch?

General fits which are fitted by giving a decent initial guess for fitting parameters in it is done by fminsearch which is a multidimensional minimizer routine.
Suppose we have a set of data points (xj , yj) and a proposed fitting function of the form y = f(x, a1, a2, a3, ...).

For example : we could try to fit to an exponential function
With two adjustable parameters a1 and a2 as is done in the example in leastsq.m below:
f(x, a1, a2) = a1ea2x

Or we could fit to a cubic polynomial in x2 with four adjustable parameters a1, a2, a3, a4 with this f:
f(x, a1, a2, a3, a4) = a1 + a2x2 + a3x4 + a4x6

## What are housekeeping functions in matlab?

Functions are those functions which do not really do math but are useful in programming.

Some functions are mentioned below:

clc - clears the command window; useful for beautifying printed output
ceil(x) - the nearest integer to x looking toward +1
close 3 - closes figure window 3
fix(x) - the nearest integer to x looking toward zero
fliplr(A)- flip a matrix A, left for right
floor(x) - the nearest integer to x looking toward -1
length(a) - the number of elements in a vector
mod(x,y) - the integer remainder of x/y; see online help if x or y are negative
rem(x,y) - the integer remainder of x/y; see online help if x or y are negative

## How Logarithmic plots can be plotted in Matlab? Explain with the help of an example?

Log and semi-log plots are plotted with the help of semilogx, semilogy, and loglog commands.

For Example
x=0:.1:8;
y=exp(x);
Semilogx(x, y);
title (’Semilogx’)
pause
Semilogy(x, y);
title(’Semilogy’)
pause
loglog(x,y);
title(’Loglog’)

## What is “rand” in Matlab?

The function rand(m,n) produces an m _ n matrix of random numbers, each of which is in the range 0 to 1. rand on its own produces a single random number.

For Example
>> y = rand, Y = rand (2, 3)
y =
0.9191
Y =
0.6262 0.1575 0.2520
0.7446 0.7764 0.6121

## Write a program to print a simulink model from an M-file

Following program will run only in Unix.
function printsys(sys)
open_system(sys);
blocks=get_param(sys,'blocks');
= size(blocks);
for i=1:r
if( get_param([sys,'/',blocks(i,:)],'blocks')~=[] )
open_system([sys,'/',blocks(i,:)])
%disp(blocks(i,:))
print('-s')
end
end
close_system(sys)

## How can you change the ratio of the axis in a 3-D plot?

For changing the ratio of the axis in a 3-D plot, you will need to change the xform property of the current axis. The property transforms the 3-D data to be plotted on the 2-D screen.

Following code will work:
function aspect3(x,y,z)
v = get(gca,'xform');
d = diag([x y z 1]);
set(gca,'xform',v*d);

## What is the process to change default settings for an object’s properties?

To change the default settings for an object, first parent of the object should be find which can be done by following code:
h=get(object's_handle,'Parent')

To set the default, type the following:
set(h,'DefaultObjectPropertyName','PropertyValue')

No spaces should be there in the Default Object Property Name expression.
For Example
set(gca,'DefaultLineLineWidth',25)

Any line plotted after this statement will have a line width of 25.

## Give an example to use grid data to contour irregularly spaced data in matlab

x,y,z => irregularly spaced data
xmin=min(x);
ymin=min(y);
xmax=max(x);
ymax=max(y);
xi=xmin:0.02*(xmax-xmin):xmax;
yi=ymin:0.02*(ymax-ymin):ymax;
zi=griddata(x,y,z,xi',yi);
contour(xi,yi,zi).

## What is pseudo random binary sequence and numeric precision in matlab?

pseudo random binary sequence : A form of generating an M-file in the new Frequency Domain System Identification Toolbox, for a specified set of lengths (2^2-1 to 2^30-1) is called pseudo random binary sequence. It is also known as mlbs (for Maximum Length Binary Sequence).

numeric precision : Numeric quantities which are represented as double precision floating point numbers is called numeric precision. On most computers, such numbers have 53 significant binary bits, which is about 15 or 16 decimal digits.

## Write a program to use a filename which is a variable as an input argument to the load, save and print functions

name = 'xyz.mat';
eval(['save ', name]);
name = 'myfigure.ps';
eval(['print ',name]);

## Define Xmath

Xmath can be fined as an interactive mathematics, scripting, and graphics environment for X Window workstations. It has features which represent a significant improvement on matlab-type software tools, including:
• Object-oriented scripting language.
• "Point-and-click" color graphics.
• Visual debugging tool.
• LNX and C-callable libraries.
• Programmable MOTIF GUI layer.

## What are the common toolboxes present in matlab and how these toolboxes can be accessed?

Various types of toolboxes available are:
• Control Systems
• Fuzzy Logic
• Image Processing
• LMI Control
• Neural Networks
• Optimization
• Partial Differential Equation
• Robust Control
• Signal Processing
• Statistics
• Symbolic Math
• System Identification
• Wavelets
To access this Toolbox, go to the MATLAB Start menu, then go to the Toolboxes submenu, then select the Toolbox which you want to use.

## How “help” command is used in various ways in matlab?

By typing “help” in different ways at matlab prompt gives following outputs:

"help" - gives a list of all the directories in which matlab can find commands (which also tells you its "search path", or a list of the directories it is looking in for commands.)
"help directoryname" - gives a list of the commands in that directory and also a short description of them.
"help commandname" - gives the help on some specific command.

## Explain about the mentioned tools in matlab: who, whos, pi, eps, type

Who: will tell you all the variables you have currently defined.
whos: will tell you the variables, their sizes, and some other info.
pi: is a function of that returns the value of pi.
eps: is a function that returns Matlab's smallest floating point number. This is useful if you have a vector that might contain zeros that is going to wind up in the denominator of something. If you add eps to the vector, you aren't actually adding anything significant, but you won't run into divide by zero problems anymore
Type: function name for any function in Matlab's search path lets you see how that function is written.

## How does backslash (\) operator works in matlab?

Backslash operator is used to solve linear systems of equations in matlab. If you want a solution for Ax = b, then type x = A\b. If A is an n by m matrix and b is a p by q matrix then A\b is defined and is calculated, if m=p. For non-square and singular systems, the operation A\b gives the solution in the least squares sense.
For Example.
>> A = [1 2; 3 4], x = [1 0]', A\x

A =

1 2
3 4

x =

1
0

ans =

-2.0000
1.5000

## What is Matlab data handling? Explain about importing ASCII data in?

Importing and Exporting ascii data in mat lab is called matlab data handling.
By typing help load, we can see how data is imported to Matlab. The data file must contain n rows with m columns of data in each row. If the file is named foo.dat, then type load foo.dat. Matlab will call the data foo.

For Example
>> foo

foo =

1 2
3 4
5 6
7 8
9 10

## Write a program in matlab to perform synthetic division of (x^2 + x + 1)/(x + 1). Which command is used for it?

Matlab can perform the synthetic division with the command deconv, giving you the quotient and the remainder.
% a=x^2+x+1 and b=x+1
a= [1, 1, 1]; b= [1, 1];

% now divides b into a finding the quotient and remainder
[q,r]=deconv (a, b)

After you do this Matlab will give you q= [1, 0] and r= [0, 0, 1],
which means that,
q = x + 0 = x and r = 0x^2+ 0x + 1 = 1 so
(x^2 + x + 1)/(x + 1) = x + [1/(x + 1)]

## What is Set and Get in Matlab?

Set and Get are also known as setter and getter functions. Setter functions are used for assigning properties whereas getter functions are used for accessing properties which are executed whenever an attempt to set or get the corresponding property is made. These are optional; they are only called if they exist. These properties can be made public by using this approach so that it is easier for clients to use the dot notation, while maintaining a level of indirection by effectively intercepting the call.

For Example
function day = get.day(obj)
day = obj.day; % We could execute other code as well.
end
function obj = set.day(obj,newday)
obj.day = newday;
end

Set-2:
1) Explain what is MatLab? Where MatLab can be applicable?
MatLab is a high-level programming language with an interactive environment for visualization, numerical computation and programming function.
Matlab can be applicable at numerous instances like
• Allows matrix manipulations
• Plotting of functions and data
• Implementation of algorithms
• Creation of user interfaces
• Analyze data
• Develop algorithm
• Create models and applications
• Interfacing with programs written in other languages ( C++, C, Java and Fortran)
2) What does MatLab consist of?
MatLab consists of five main parts
• MatLab Language
• MatLab working environment
• Handle Graphics
• MatLab function library
• MatLab Application Program Interface (API)
3) Explain MatLab API (Application Program Interface)?
MatLab API is a library that enables you to write Fortran and C programs that interact with MatLab. It contains the facilities for calling routines from MatLab, for reading and writing Mat files and calling Matlab as a computational engine.
4) What are the types of loops does Matlab provides?
Matlab provides loops like
• While Loop
• For Loop
• Nested Loops
5) List out the operators that MatLab allows?
Matlab allows following Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operations
• Set Operations

Simulink is an add-on product to MatLab, it provides an interactive, simulating, graphical environment for modeling and analyzing of dynamic systems.
7) In MatLab is it possible to handle multi-dimensional arrays?

Yes, it is possible in MatLab to handle multi-dimensional arrays. Matlab’s internal data structure is limited to a two-dimensional matrix. But to handle multi-dimensional arrays in Matlab, you can create your own functions in Matlab language.
8) Mention what is the sign convention used in MatLab’s fft routines?
The sign convention used in MatLab’s fft routines are defined as sum(x(i)*exp (-j*i*k/N)) and not sum (x(i)exp(j*i*k/N)). The first version is used by engineers, and the second is used by mathematician.
9) What are the four basic functions to solve Ordinary Differential Equations (ODE)?
The four basic functions that MatLab has to solve ODE’s are
• ODE23
• ODE45
10) Explain how polynomials can be represented in MatLab?
A polynomial in MatLab is denoted by a vector. To create a polynomial in MatLab enter each co-efficient of the polynomial into the vector in descending order
11) What is the type of program files that MatLab allows to write?
Matlab allows two types of program files
• Scripts: It is a file with .m extension. In these files, it writes series of command that you want to execute together. It does not accept inputs and do not return any outputs
• Functions: They are also files with .m extension. Functions can accept inputs and return outputs.
12) Explain how to modify the MatLab Path?
To modify the MatLab Path use the PathTool GUI. Also, you can use add path directories from the command line and add the path to rc to write the current path back to ‘pathdef.m.’ In the case if you don’t have permission to write for ‘pathdef.m’ then pathrc can be written into a different file, you can execute from your ‘startup.m.’
13) Explain what is LaTex in MatLab?
MatLab handles naturally simple LaTex encoding which allows introducing greek letters or modifying the font size and appearance in plots.
14) Explain how you can pre-allocate a Non-Double Matrix?
Pre-allocating a block of memory for holding a non-double matrix is memory efficient. While allocating blocks of memory for a matrix, zeros are pre-allocated to a matrix.
The functions to pre allocate memory is int8(), example matrix =int8(zeros(100));
Repmat function is used to create a single double matrix, example matrix2=repmat(int8(0), 100, 100)
15) What is Xmath-Matlab? Mention the Xmath features?
For Xwindow workstations, Xmath is an interactive scripting and graphics environment.
Following are the X-math features
• Scripting language with OOP features
• Libraries that are LNX and C language compatible
• A debugging tools with GUI features
• Color graphics can be pointed and clickable
16) Name the graphic system used in MatLab?
Graphic system used in MatLab is known as handle graphics. It has a high level and low-level commands.
• High Level Commands: High level command performs image processing, data visualization and animation for 2D and 3D presentation graphics
• Low Level Commands: Full customization of the appearance of graphics and building of complete graphical user interface
17) Explain what is M-file and MEX files in MatLab?
M files: They are just a plain ASCII text that is interpreted at run time. They are like sub-programs stored in text files with .m extensions and are called M-files. For most of the MatLab, development M-files are used.
MEX files: They are basically native C or C++ files which are linked directly into the MatLab application at runtime. MEX files have efficiency to crash the MatLab application.
18) Explain what is Interpolation and Extrapolation in Matlab? What are their types?
• Interpolation: Taking out function values between different data points in an array is referred as Interpolation
• Extrapolation: Finding function values beyond the endpoints in array is referred as Extrapolation
The two types of Interpolation and Extrapolation are
• Linear Interpolation and Extrapolation
19) List out some of the common toolboxes present in Matlab?
Some of the common toolboxes in Matlab are
• Control System
• Fuzzy Logic
• Image Processing
• LMI control
• Neural Networks
• Robust Control
• System Identification
20) What is Get and Set in Matlab?
Get and Set are referred as getter and setter functions. For assigning properties, setter functions are used while for accessing properties getter functions are used.

Set-3 :
Question -1: Mention type of operators used in MATLAB environment.
Answer -1: MATLAB supports relational, arithmatic, bitwise and logical operators.
Question -2: Mention control flow statements supported in MATLAB.
Answer -2: Like C and other languages, MATLAB supports if statement, switch statement, for loop and while loop.
Question -3: What are MEX files in MATLAB.
Answer -3: Using MEX files which are C or C++ program, one can call them directly in MATLAB during runtime.
Question -4: What is the main difference between script and function in MATLAB?
Answer -4: Both have got same extension as (.m). Script file type in matlab consists of series of commands. They do not take any arguments neither they return any arguments or any values. Function is like any other programming language function. It takes arguments as well as returns arguments.
Question -5: Can Multi-dimensional arrays supported in MATLAB?
Answer -5: No, it do not support. It supports two-dimensional type of matrix. The option is option with programmer to write the function of their own to utilize multi-domensional array feature as per application of use.
Question -6: How one can save the matlab environment data into a matlab data file and call the same in any other matlab program whenever required?
Answer -6: MATLAB programmer can use 'save' and 'load' for doing the above.
Question -7: Which is the operator by which element to element multiplication can be done using MATLAB?
Answer -7: The operator is ".*". When two matrices 'A' and 'B' are required to be multiplied element by element, it can be written as follows: A .* B
Question -8: If one is appearing for Digital Signal Processing (DSP) position, he may often be asked "what is the difference between rand and randn" ?
Answer -8: The functions such as rand and randn used to model AWGN channel. The function 'randn' generates random numbers with normal distribution with mean value equal to zero and variance value of one. The function 'rand' generatea random numbers with uniform distribution. These are used in AWGN function of matlab.
Question -9: Mention function used for interpolation and decimation in MATLAB.