Matlab interview questions and answers - Matlab FAQs

“The input was 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;
---Your code here--
X = 'A'; % X changed from type double to char
-----Your code here----

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
  • Quadratic 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]);
eval(['load ', 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
>> load foo.dat
>> 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
Post your comment
Discussion Board
a question about matlab function
I have used diff(y,x) for a function in matlab and it has give me a answer that has abs(a,b) in it.
wht is this function according to its two arguments?
ali 08-1-2016
matlab
How can a function block diagram in Matlab achieved?
ali 09-10-2015

You may like