Interview Questions on MatLab

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have presented the most important Interview Questions on MatLab along with detailed answers.

Theory questions

Q1. What is MATLAB, and what are its uses?

Answer: MATLAB is short for Matrix Laboratory. The MathWorks-developed MATLAB is a proprietary, multi-paradigm programming language and environment for numerical computation. It is possible to,

  • manipulate matrices
  • visualize functions and data
  • apply algorithms
  • build user interfaces
  • and communicate with other programming languages

using MATLAB.

Q2. What are some of the unique advantages of MATLAB?

Answer:

  1. MATLAB offers great performance while providing extensive UI options. Hence it becomes easy to quickly implement, debug and test full-scale algorithms.
  2. The availability of libraries for a wide range of domains(like signal processing, image processing, etc) and is compatible with various external platforms and devices makes prototyping experimental projects comfortable.

Q3. Is MATLAB an OOP language?

Ans: The MATLAB language enables you to create programs using both procedural and object-oriented techniques.

Q4. Can you create GUI using MATLAB?

Ans: Yes, Matlab provides a good environment for creating the GUI. This is because it automatically generates the code for the design of the GUI.

Q5. What is SIMULILNK?

Ans: Simulink is a MATLAB-based graphical programming environment for modeling, simulating, and analyzing multidomain dynamical systems. Simulink is integrated with MATLAB.

Q6. Can you build Custom Neural Networks in MATLAB?

Ans: Yes, Neural Networks with user-defined architectures can be defined in MATLAB.

Q7. What are the possible extensions for MATLAB files?

Ans: .m, .mlx, mat are common extensions for matlab files

Q8. What is the language MATLAB is written in?

Ans:

In contrast to other coding languages, MATLAB's native coding language is easy to use. In addition, you may select the language in which you want to code. It has built-in compilers for the majority of widely used programming languages, including C, C++, and java. The language can be changed to suit your tastes.

Code questions

Q1. How to write and call a function in MATLAB?

Ans:
Function definition,

function < output > = < function_name >( < function_parameters > )
<function body>
end

Function call,

< result_variable > = < function_name >( < input_function_parameters > )

eg:
defining a funciton to add 2 inputs,

function sum = my_add(a, b)
sum = a+b; 
end

function call,

my_sum = my_add(1, 2)

result,

my_sum = 3

Q2. How to create a 2D-plot in MATLAB?

Ans:

Plot definition,

plot(< variable_1 >, < variable_2 >, ...)

Here variable_1 is plotted along the horizontal axis and variable_2 is plotted on the vertical axis.

eg:

x = 1
y = 1
plot(x, y, ".")

result,

Q3. How to create a 3D-plot in MATLAB?

Ans:

Plot definition,

plot3(< variable_1 >, < variable_2 >, < variable_3 >)

eg:

x = 1
y = 1
z = 1
plot3(x, y, z, ".")

result,

Q4. How to comment in MATLAB ?

Ans:

Single Line Comment

A comment is defined using % anything following it in the same line will not be complied as code.

Multi Line Comment

The text enclosed withing %{ and %} are not complied as code

Q5. How to create a matrix in MATLAB ?

Ans:

Matrices in general are referred to as Arrays and Multi-Dimensional arrays in MATLAB. Array elements are defined enclosed in square brackets []. different elements are distinguished by either whitespace or commas and ,.

When defining matrices elements are defined row-wise i.e., the elements of rows are filled first. successive rows are distinguished by semicolon ;

eg of a 2x3 matrix,

< variable_name > = [1 3 5; 2 4 6;]

Q6. How are elements of matrices accessed in MATLAB?

Ans:

  • MATLAB arrays are 1-indexed

matrice elements are accessed using < variable_name >( dim1 , dim2 , dim3, ...)

eg:
accessing the 2 row and 2 column element of M

M = [1, 2 ,3; 4, 5, 6; 7, 8, 9]
M(2, 2)

Q7. How to slice matrices in MATLAB?

Ans:

Matrices are sliced using colon : like,

< sliced_variable > = < original_variable >(start_index:end_index, ... )

eg:
slicing the first 2 rows and columns of M from previous eg

N = M(1:2,1:2)

result,

N = [1, 2; 4, 5]

Q8. How to suppress the output of a MATLAB code?

Ans:

following the statement by semicolon ; will suppress the output being generated.

eg:

a = 10;

result:
The output will be suppressed and nothing will be displayed.

Q9. How to define the precision of outputs in MATLAB?

Ans:

digits(d) sets the precision used by vpa to d significant decimal digits. The default is 32 digits.

eg:

pi_32 = vpa(pi)
digits(5)
pi_5 = vpa(pi_32)

result:

pi_5 = 3.1416

Q10. How to perform element-wise multiplication in MATLAB?

Ans:

The . operator as the prefix is used to signify the arithmetic operator is required to be performed element-wise.

eg:

A = [1; 2]
B = [2; 3]
C = A.*B

result,

C = [2; 6]

Q11. How to stop a program in MATLAB ?

Ans:

To end a program in MATLAB, you may either use the quit command directly or a desktop shortcut like Ctrl + C.

Q12. How to read and display an image in MATLAB?

Ans:

An image can be read by,

< variable_name > = imread("< Directory/ Image_name >");

An image can be displayed by,

imshow(< variable_name >)

Q13. How to read an audio file in MATLAB?

Ans:

An audio file can be read by,

[< sampled_data >, < sample_rate >] = audioread("< Directory/ AudioFile_name >")

Q14. How to read an Excel file in MATLAB?

Ans:

originally it can be done by,
< variable_name > = xlsread("< Directory/ ExcelFile_name >")

but it is recommended to use readtable, readmatrix, or readcell based on the application instead.

Q15. What are the types of loops available in MATLAB?

Ans:

MATLAB offers two basic loops

  1. For loop
  2. While loop

eg:
for loop,

for i = 1:5
    i
end

while loop,

i = 1
while i<5
    i = i+1
end

Q16. Are nested loops supported in MATLAB?

Ans: Yes

eg:

i = 1
while i<5
    i = i+1
    for j = 1:5
        j
    end
end

Q17. How to generate a random number in MATLAB?

Ans:

rand is used for Uniformly distributed random numbers, randn is used for Normally distributed random numbers, and randiis used for Uniformly distributed pseudorandom integers.

eg:

res = randi()

result:

res = 9

Q18. How to control the random number generation in MATLAB?

Ans:

seed for the random number generation is specified by rng(< seed >)\

eg:

rng(1)

result:
This ensures that the random numbers generated is in accordance with the seed specified. In other words, it makes it so that the numbers will be consistent with each generation which is used to verify results during testing.

Q19. How to convert different data types in MATLAB?

Ans:

Data type of different variables can be converted using the help of inbuilt commands. some of them are,

command purpose
string String array
char Character array
cellstr Convert to cell array of character vectors
int2str Convert integers to characters
mat2str Convert matrix to characters
num2str Convert numbers to character array

eg:

my_char = ['a', ' ', 's', 't', 'r']
my_sting = string(my_char)

result:
this command combines the array of characters into a string.

Q20. How to time code in MATLAB?

Ans:

functions can be timed using the timeit command as so,

< function_variable > = @() < function_name >(< input_function_parameters >);
timeit(< function_variable >)

portions of code can be timed using, tic and toc commands
finally, the difference will give the run time of the enclosed code.

Q21. What are different storage functions in MATLAB?

Ans:

  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.

Q22. How to get the inverse of a matrix in MATLAB?

Ans:

The inverse of a matrix can be obtained by,

< inverted_matrix_name > = inv(< original_matrix_name >)

eg:

A = [1, 0; 0, 1]
B = inv(A)

result,

B = [1, 0; 0, 1]

Q23. How to perform dot and cross product in MATLAB?

Ans:

dot product returns a scalar output and is done as so,

< result_varaible_name > = dot(< variable_1 >, <variable_2 >)

similarly, the cross product is done as,

< result_varaible_name > = cross(< variable_1 >, <variable_2 >)

eg:

A = [1, 0; 0, 1]
B = [0, 1; 1, 0]
res = dot(A, B)

result,

res = [0, 0]

Q24. How to perform convolution operation in MATLAB?

Ans:

< result_varaible_name > = conv(< variable_1 >, <variable_2 >, shape*)

Here, variable_2 is the filter and shape is an optional parameter for defining the type of convolution operation. The possible values are "same", "valid" and "full"

eg:

A = [1, 1, 2, 2]
B = [1, 2, 1]
res = conv(A, B)

result,

res = [1, 3, 5, 7, 6, 2]

Q25. How to perform n-dimensional convolution operation in MATLAB?

Ans:

< result_varaible_name > = convn(< variable_1 >, <variable_2 >)

eg:

A = [1, 1; 2, 2]
B = [1; 1]
res = convn(A, B)

result:

res = [1, 1; 3, 3; 2, 2]

Q26. How to use Trignometric funcitons in matalb?

Ans:

The following are the trignometric function variants available in MATLAB,

command operation
sin Sine of argument in radians
sind Sine of argument in degrees
sinpi Compute sin(Xxpi) accurately
asin Inverse sine in radians
asind Inverse sine in degrees
sinh Hyperbolic sine
asinh Inverse hyperbolic sine

the same are available for all cos, tan, csc, sec and cot

Q27. How to convert Degrees and Radians in MATLAB?

Ans:

deg2rad is used to Convert angle from degrees to radians and
rad2deg is used to Convert angle from radians to degrees

eg:

res = deg2rad(360)

result,

res = 6.2832

Q28. How to get the diagonal elements of a matrix in MATLAB?

Ans:

< result_varaible_name > = diag(< input_matrix_name >)

eg:

A = [1, 0; 0, 1]
res = diag(A)

result,

res = [1; 1]

Q29. How to get the transpose of a matrix in MATLAB?

Ans:

the transpose of a matrix in MATLAB can be obtained in the following ways

  1. < transpose_matrix_name > = transpose(< input_matrix_name >)
  2. < transpose_matrix_name > = < input_matrix_name >.'

eg:

A = [1, 2; 3, 4]
res = transpose(A)

result,

res = [1, 3; 2, 4]

Q30. How to find the eigen values of a matrix in MATLAB?

Ans:

The eigen values of a matrix can be found using,

< result_varaible_name > = eig(< input_matrix_name >)

eg:

A = [1, 0; 0, 1]
res = eig(A)

result,

res = [1; 1]

Q31. How to get the real part of a variable in MATLAB?

Ans:

The real component can be obtained by,

< result_varaible_name > = real(< variable_1 >)

eg:

A = 10 + 15i
res = real(A)

result,

res = 10

Q32. How to get the complex part of a variable in MATLAB?

Ans:

The complex part can be obtained by,

< result_varaible_name > = imag(< variable_1 >)

eg:

A = 10 + 15i
res = imag(A)

result,

res = 15

Multiple choice questions (MCQs)

Q1. Which of the following are correct ways to uniformly sample n points between 2 points [a, b]

(a) linspace(a, b, n)

(b) n*(a, b)

(c) [(a-b)/n]*n

(d) a: (a-b)/n: b

Ans: Options - a and d

Explanation: syntax

Q2. What is the output of the following code?

size('')

(a) 1 1

(b) 0 0

(c) 1

(d) error

Ans: Option - b

Explanation: The type of input that was provided is returned by the size command. The input string here is an empty string, however, the size function will return the number of rows and columns existing in the string, which in this case is 0 and 0.

Q3. What is the final value of a?

a = 0
for i = 0:2:10
    for j = 1:5
        a = a + 2
    end
end

(a) error

(b) 10

(c) 60

(d) 50

Ans: Option - c

Explanation: The first loop has 6 iterations and the second nested loop has 5 iterations. In total 30 updates of a. a = 30*2 = 60

Q4. What is the final value of c?

a = 1
b = 2
a += 1
b = a + b
c = b + a

(a) error

(b) 6

(c) 5

(d) 4

Ans: Option - a

Explanation: we cannot perform unary addition in MATLAB using += or similar operations.

Q5. The correct way to produce a 1 complete sine wave plot when the variables are declared as follows is

v1 = 0:0.01:2*pi
v2 = sin(v1)

(a) plot(v2, v1)

(b) plot(v1, v2)

(c) plot([v1, v2])

(d) plot([v2, v1])

Ans: Option - b

Explanation: syntax

Q6. What is the expected output for b in the following code?

a = linspace(0, 100, 101)
b = (a>50)

(a) array with 101 elements, first 50 are 0

(b) array with 101 elements, first 51 are 1

(c) array with 100 elements, first 50 are 1

(d) array with 101 elements, first 51 are 0

Ans: Option - d

Explanation: 51(in 52nd index) valued element will be the starting point of 1s, hence 51 0s in 101 elements.

Q7. Which of the following will output all odd numbers less than 100?

(a) 1:2:99

(b) (1:100)/2 < 100

(c) odd(0, 100)

(d) None of the above

Ans: Option - a

Explanation: syntax

Q8. What is the expected output of the following code?

true & false & true & false

(a) true

(b) false

(c) 1

(d) 0

Ans: Option - d

Explanation: left to right

Q9. What is the expected output of the following code?

true | false & true | false

(a) true

(b) false

(c) 1

(d) 0

Ans: Option - c

Explanation: & has greater precedence than |

Q10. Both & and && are the same True/False?

(a) False

(b) true

Ans: Option - a

Explanation: & is a logical elementwise operator, while && is a logical short-circuiting operator

Explain the code

Try not to run the code

Hint: try a few manual iterations

Q1. Explain the following code

a = 0;
b = 1;
n = 10;

for i = 1:n
    a
    c = a + b;
    a = b;
    b = c;
end

Ans: This is a simple implementation of the Fibonacci function up to n digits, typically identified by the declaration of a and b to 0 and 1 along with their update patterns.

Q2. Here input x is an array, include the expected output in your answer,

num = numel(x);
for j = 0 : num-1
    for i = 1: num-j-1
        if x(i)>x(i+1)
            temp = x(i);
            x(i) = x(i+1);
            x(i+1) = temp;
        end
    end
end

Ans: The following is the algorithm for bubble sort (identified by the conditional temp variable for swapping the element indices as well as 2 loops) and the expected output is the sorted array of x (stored in x as well).

Q3. Here input x is an array, include the expected output in your answer,

num = length(x);
tmp = x(1);
ind = 1;
for i = 1:num
    if tmp < x(i)
        tmp = x(i);
        ind = i;
    end
end

Ans: The following code is the algorithm for finding the greatest value along with its index in a given input. Logically simplest implementation of the greatest and lowest value(change the condition to - tmp > x(i) ) index pair identification algorithm is formulated as above.

Q4. Explain in terms of Machine Learning,

lim = rand()*10
x = linspace(-lim, lim, 100);
for i = 1:length(x)
    exp_val = exp(-x(i));
    y(i) = 1/(1+exp_val);
end
plot(x, y)

Ans: The first two lines synthesize data and within the loop the sigmoid function is applied to the input. In essence, the code is generating a random sigmoid plot in the range [-lim, lim]

Q5. Here input x is an arry, explain the following code,

mid = floor(length(x)/2);
if sum(x(1:mid)) > sum(x(mid:end))
    y = 0;
else 
    y = 1;
end

Ans: The code compares the sum of the elements of half of the input and returns value 0 if the sum of elements in the first half of the input is greater and 1 otherwise.

Q6. Explain in terms of Machine Learning,

W = [0.5 0.25; 0.25 0.5];
X = [.12; .74];
B = 1;  
Z = W + B;

Ans: This is the illustration of broadcasting and works accordingly with some operators in matlab. Here, W represents the weights and B bias of a layer. Corresponding Z(preactivation value of neuron) is calculated.

Q7. Include the expected output in your answer,

(2*Inf)-(1*Inf)

Ans: The output is NaN, Inf is used as an initial assignment in some cases and its value is not-defined/vaguely defined, equivalently in matlab terms NaN.

Q8. Include the expected output in your answer,

pos = [0 0;    % startpoint
       10 10]; % endpoint
nturns = 5;

dp = diff(pos,1,1);
R = hypot(dp(1), dp(2));
phi0 = atan2(dp(2), dp(1));
phi = linspace(0, nturns*2*pi, 10000);

r = linspace(0, R, numel(phi)) ;
x = pos(1,1) + r .* cos(phi + phi0) ;
y = pos(1,2) + r  .* sin(phi + phi0) ;
plot(x,y,'b-', 'MarkerSize', 3) ;

Ans: This plots a spiral between the defined start point and endpoint. The variables used often provide hints of the purpose of the code. Additionally, we are adding corresponding circular components using trigonometric values.

Q9. Here input x is an array, explain the following code,

unq = unique(x);
ind_o = mod(unq,2)==1
unq_new = unique(unq.*ind_o)
n_unq_o = length(unq_new)

Ans: The output is the number of unique odd elements including 0.

Q10. Here input x is an array, explain the following code,

k = x(:,1);
x(:,1) = x(:,end);
x(:,end) = k;

Ans: The extreme elements are swapped.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.