Matlab Pune University MCQs

Matlab Pune University MCQs

Matlab Pune University MCQs

 This set of MATLAB Multiple Choice Questions & Answers  focuses on “Input and Output”.


1. MATLAB stands for?

a) matrix laboratory

b) math library

c) matric library

d) matrix library

Answer: a

Explanation: MATLAB stands for matrix laboratory which is multi-paradigm numerical computing environment and fourth-generation programming language.

2. Which command is used to clear a command window?

a) clear

b) close all

c) clc

d) clear all

Answer: c

Explanation: clc clears all input and output from the Command Window display and provide a “clean screen”. After using clc, you cannot use the scroll bar to see the history of functions, but you still can use the up arrow key, ↑, to recall statements from the command history.

3. To determine whether an input is MATLAB keyword, command is?

a) iskeyword

b) key word

c) inputword

d) isvarname

Answer: a

Explanation: Command iskeyword uses the MATLAB command format. iskeyword returns a list of all MATLAB keywords. It gives output in the form of 1 and 0.

4. Command used to display the value of variable x.

a) displayx

b) disp

c) disp x

d) vardisp

Answer: b

Explanation: disp displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, but this displays a leading “X =”, which is not always ideal. If a variable contains an empty array, disp returns without displaying anything.

5. Which of the following statements shows the result of executing the following line in the editor window?


size = [1 3]’        ;

size(size)

a) error

b) 1 3

c) 3 1

d) 3 3

Answer: a

Explanation: Executing the command iskeyword size returns 0, i.e., size is not a MATLAB keyword. Same command should not be used as a variable in MATLAB, so there is a error message.

6. Executing in the command window the following code returns.


 a = [1:3]’ ;
size(a)

a) error message

b) 1 3

c) 3 1

d) 31

Answer: c

Explanation: It forms a 2×1 matrix of 3 and 1 because transpose condition is there, so size returns transposed value.

7. Command is used to save command window text to file.

a) saveas

b) texttofile

c) diary

d) todiary

Answer: c

Explanation: The diary function creates a log of keyboard input and the resulting text output, with some exceptions. The output of diary is an ASCII file, suitable for searching in, printing, inclusion in most reports and other documents.

8. Executing in the editor window the following code returns.


a = 1; sin(a) a = 2;

a) 0.4815

b) 0.8415

c) 1

d) 0.9093

Answer: b

Explanation: It chooses the value of a is 1 because it follows line pattern as it neglects 2 because this command is written after sin command.

9. To stop the execution of a MATLAB command, used keys?

a) ctrl+c

b) ctrl+s

c) ctrl+b

d) ctrl+enter

Answer: a

Explanation: Ctrl+C stop execution for files that run a long time, or that call built-ins or MEX-files that run a long time. Ctrl+Break is also used to stop the execution.

10. Which is the invalid variable name in MATLAB?

a) x6

b) last

c) 6x

d) z

Answer: c

Explanation: A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case sensitive, so A and a are not the same variables, and in 6x digit is followed by a letter which is invalid.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Arithmetic – 1”.


1. What would be the output of the following code ?


A = [0 1; 1 0] ; B=2 ; C = A + B

a)


   1 2

   4 5

b)


    2 3

    3 2

c)


    3 2

    3 2

d)


    3 2

    2 3

Answer: b

Explanation: C = A + B adds arrays A and B and returns the result in C.

C = plus is an alternate way to execute A + B, but is rarely used. It enables operator overloading for classes.


2. What would be the output of the following code ?


A = [1 0 2] ; b = [3 0 7] ; c=a.*b;

a) [2 0 21]

b) [3 0 14]

c) [14 0 3]

d) [7 0 3]

Answer: b

Explanation: C = a.*b multiplies arrays a and b element by element and returns the result in C.

3. What would be the output of the following code ?


a=1:5 ; c=a.^2

a) [1 25]

b) [1 2 3 4 5]

c) [25 16 9 4 1]

d) [1 4 9 16 25]

Answer: d

Explanation: c=a.^2 raises each element of a to the corresponding power i.e. 2. It will square each element.

[1 2 2 2 3 2 4 2 5 2 ] = [1 4 9 16 25].

4. What would be the output of the following code ?


A = [1 1 0 0]

B = [1 ;2 ;3 ;4]

C=A*B

a) 0

b) [1 0 0 0]

c) 3

d) [1 2 0 0]

Answer: c

Explanation: The result is a 1-by-1 scalar, also called the dot product or inner product of the vectors A and B. Alternatively, you can calculate the dot product A • B with the syntax dot.

Multiply B times A.

5. What would be the output of the following code ?


A = [1 2; 3 4]

C = A^2

a) [7 10; 15 22]

b) [1 4; 9 16]

c) [16 9; 4 1]

d) [22 15; 10 7]

Answer: a

Explanation: C = A 2 computes A to the 2 power and returns the result in C. The syntax A2 is equals to A*A.

A 2 = [1 2; 3 4] *[1 2; 3 4] [7 10; 15 22].

6. What would be the output of the following code ?


A=1:5;

B=cumprod(A)

a) b=[1 2 6 24 120]

b) b=[1 2 3 4 5]

c) b=[5 4 3 2 1]

d) b=[120 24 6 2 1]

Answer: a

Explanation: B = cumprod returns the cumulative product of A starting at the beginning of the first array dimension in A whose size does not equal 1. B is the product of A and A, while B is the product of elements A through A.

7. Create an array of logical values.


A = [true false true; true true false]

A = 1     0     1

    1     1     0

B = cumprod(A,2)

Find the cumulative product of the rows of A.

a)


      B = 1     0     0

          0     1     0

b)


      B = 1     0     0

          1     1     0

c)


      B = 1     0     0

          1     1     1

d)


      B = 1     1     0

          1     1     0

Answer: b

Explanation:

      B = 1     0     0

          1     1     0

The output is double.

class

ans = double.



8. Find the cumulative sum of the columns of A.


  A =1     4     7

     2     5     8

     3     6     9

B = cumsum(A)

a)


B = 1     4     7

    3     8    15

    6    15    24

b)


B = 1     4     7

    4     9    15

    4    15    24

c)


B = 1     4     7

    3     9    15

    6    15    29

d)


B = 1     4     7

    3     9    15

    6    15    24

Answer: d

Explanation: B = cumsum returns the cumulative sum of A starting at the beginning of the first array dimension in A whose size does not equal 1. If A is a matrix, then cumsum returns a matrix containing the cumulative sums for each column of A. B is the sum of A and A, while B is the sum of A, A, and A.


9. Create a 4-by-2-by-3 array of ones and compute the sum along the third dimension.


A = ones(4,2,3);

S = sum(A,3)

a)


S = 3     3

    3     3

    3     3

    3     3

b)


S = 3     4

    3     4

    3     4

    3     4

c)


S = 2     3

    2     3

    2     3

    2     3

d)


S = 7     3

    5     3

    6     3

    3     3

Answer: a

Explanation: S = sum returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a multidimensional array, then sum operates along the first array dimension whose size does not equal 1, treating the elements as vectors. This dimension becomes 1 while the sizes of all other dimensions remain the same.


This set of MATLAB Interview Questions and Answers focuses on “Arithmetic – 2”.


1. Round each value in a duration array to the nearest number of seconds greater than or equal to that value.


t = hours(8) + minutes(29:31) + seconds(1.23);

t.Format = 'hh:mm:ss.SS'

t = 08:29:01.23   08:30:01.23   08:31:01.23

Y1 = ceil(t)

Y2 = ceil(t,'hours')

a)


     Y1 =  08:29:02.00   08:30:02.00   08:31:02.00 

     Y2 =  09:00:00.00   09:00:00.00   09:00:00.00

b)


     Y1 =  08:29:02.00   08:30:02.00   08:31:02.00 

     Y2 =  08:29:01.23   08:30:01.23   08:31:01.23

c)


     Y1 =  08:29:01.23   08:30:01.23   08:31:01.23

     Y2 =  08:29:01.23   08:30:01.23   08:31:01.23

d)


     Y1 =  008:29:01.23   08:30:01.23   08:31:01.23

     Y2 =  09:00:00.00   09:00:00.00   09:00:00.00

Answer: a

Explanation: Y = ceil rounds each element of t to the nearest number of the specified unit of time greater than or equal to that element. Round each value in t to the nearest number of hours greater than or equal to that value.


2. What would be the output of the following code ?


X = [1.4+2.3i 3.1-2.2i -5.3+10.9i]

X = 1.4000 + 2.3000i   3.1000 - 2.2000i  -5.3000 +10.9000i

Y = fix(X)

a) Y = 1.0000 + 2.0000i 3.0000 – 4.0000i -5.0000 +10.0000i

b) Y = 2.0000 + 3.0000i 3.1000 – 2.2000i -5.3000 +10.9000i

c) Y = 1.0000 + 2.0000i 3.0000 – 2.0000i -5.0000 +10.0000i

d) Y = 2.0000 + 3.0000i 3.1000 – 2.2000i -5.3000 +10.9000i

Answer: c

Explanation: Y = fix rounds each element of X to the nearest integer toward zero. For positive X, the behavior of fix is the same as floor. For negative X, the behavior of fix is the same as ceil.

3. Compute 24 modulo 5.


b = mod(24,5)

a) b = 3

b) b =4

c) b =5

d) b =6

Answer: b

Explanation: b = mod returns the remainder after division of a by m, where a is the dividend and m is the divisor. This function is often called the modulo operation and is computed using b = a – m.*floor. The mod function follows the convention that mod returns a.

4. What would be the output of the following code ?


X = [1 2 3;4 5 6;7 8 9];

Y = [9 8 7;6 5 4;3 2 1];

R = rem(X,Y)

a)


   R = 1     2     1

       4     0     9

       1     0     0

b)


   R = 1     2     3

       3     0     2

       1     0     0

c)


   R = 1     2     3

       4     1     2

       1     1     0

d)


   R = 1     2     3

       4     0     2

       1     0     0

Answer: d

Explanation: R = rem returns the remainder after division of X by Y. In general, if Y does not equal 0, R = rem returns X – n.*Y, where n = fix. If Y is not an integer and the quotient X./Y is within round off error of an integer, then n is that integer. Inputs X and Y must have the same dimensions unless one of them is a scalar double. If one of the inputs has an integer data type, then the other input must be of the same integer data type or be a scalar double.


5. If one operand is a scalar and the other is not, then MATLAB applies the scalar to every element of the other operand. This property is known as ______________

a) operand divergence

b) scalar expansion

c) vector expansion

d) dimension declaration

Answer: b

Explanation: If one operand is a scalar and the other is not, then MATLAB applies the scalar to every element of the other operand. This property is known as scalar expansion because the scalar expands into an array of the same size as the other input, then the operation executes as it normally does with two arrays.

6. Matrix operations follow the rules of linear algebra and are not compatible with multidimensional arrays.

a) true

b) false

Answer: a

Explanation: Matrix operations follow the rules of linear algebra and are not compatible with multidimensional arrays. The required size and shape of the inputs in relation to one another depends on the operation.

7. Conversion Function int16 uses_________ range of value?

a) -2 7 to 2 7 -1

b) -2 15 to 2 15 -1

c) -2 31 to 2 31 -1

d) 0 to 2 16 -1

Answer: b

Explanation: Conversion Function int16 having class of signed 16-bit integer. And signed 16-bit integer follows -2 15 to 2 15 -1 range.

8. Largest and smallest values for integer classes is 127 to -128.

a) True

b) False

Answer: a

Explanation: Obtain these values with the intmax and intmin functions:

intmax

ans = 127

intmin –

ans = 128.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Algebra”.


1. What is the difference between syms ‘x’ and sym ‘x’?

a) there is no difference, they are the same functions

b) they are equivalent

c) syms ‘x’ makes the declaration long lasting while sym ‘x’ makes the declaration short lasting

d) syms ‘x’ makes the symbol short lasting while sym ‘x’ makes the declaration long lasting

Answer: c

Explanation: sym ‘x’ makes the declaration short lasting. If it is assigned to a variable, x say, the function is equivalent to syms ‘x’. This makes syms ‘x’ long lasting.

2. What is the nature of the arrangement of the coefficients to store the following expression in MATLAB?


y= 3x5 + x2 + 6

a) y=[3,0,0,1,0,6]

b) y=[3,1,6]

c) y=[3;0;0;1;0;6]

d) y=[6,0,1,0,0,3]

Answer: a

Explanation: To enter the co-efficient of a polynomial, the variable terms are arranged in descending order of the power of the variable. It cannot be a column vector. If the descending order is not consecutive, one has to put 0 within the row vector to indicate that the co-efficient of the missing order is zero.

3. In the function vpa(‘9 81 ’,10), why do we put 9 81 within inverted commas?

a) We can choose to not put the value within a pair of single inverted comma

b) We do it so that we don’t get an approximated value

c) We do it to get the exact value as MATLAB computes exact values, of numerical expressions, when declared within a string

d) We do it to get a floating-point approximated value, approximated to 14 digits

Answer: c

Explanation: Variable precision arithmetic in MATLAB is perfected by computing exact values and exact values are evaluated if the numerical expression is within a string. By not placing the pair of inverted commas, we get a floating point approximated value.

4. How would you simplify log(x 20 ) – log(x 13 ) – log(x 7 ) in MATLAB? 

a) simplify(log(x 20 )-log(x 13 )–log(x 7 ));

b) log(x 20 ) – log(x 13 ) – log(x 7 )

c) simplify(log(x 20 )-log(x 13 )–log(x 7 ),’IgnoreAnalyticConstraints’,true)

d) simplify(log(x 20 )-log(x 13 )–log(x 7 ))

Answer: c

Explanation: Option simplify(log(x 20 )-log(x 13 )–log(x 7 ),’IgnoreAnalyticConstraints’,true) would evaluate to 0. The cases are used to produce a greater simplified expression for a polynomial. simplify(log(x 20 )-log(x 13 )–log(x 7 )) does not give any different output but the expression itself. Option log(x 20 ) – log(x 13 ) – log(x 7 ) is incorrect since the powers should be represented as log(x 20 ) in MATLAB.

5. What happens if we don’t assign a variable to an expression which evaluates a numerical value?

a) MATLAB shows error

b) Nothing happens

c) The evaluated values are assigned to a variable ans automatically

d) Depends on the numerical value

Answer: c

Explanation: This is common for MATLAB. The evaluated numerical values are assigned to a variable ans if there is no body in the right hand side of a numerical expression. So the options MATLAB shows error is false.

6. MATLAB sees a ________ ordered variable as a vector of dimension n*1.

a) n th ,  th

b) n th ,  th

c)  th , n th

d) n th ,  th

Answer: c

Explanation: The row vector which consists of the co-efficients of variables of a  th ordered polynomial in descending order is an nx1 vector where the last term is a constant term of the expression. The rest of the options are incorrect by the above statement.

7. What will be the output for the below block of code?


P=[1 3 2]; r=roots(P);

a) r=[-2,-2]

b) r=[-2 -1]

c) There is an error in the code

d)


   r = -2

       -1

Answer: d

Explanation: The function roots generate a column vector, and not a row vector, containing the roots of a polynomial. So option a and b cannot be the answer and there is no error in the code. The answer is option d.

Output:

   r = -2

       -1


8. Name the functions used, for multiplication and division of two polynomials in MATLAB.

a) conv and deconv

b) mult and div

c) conv and div

d) mult and div

Answer: a

Explanation: Multiplication in a time domain is convolution in a frequency domain. This is the reason for the existence of MATLAB functions conv, for multiplication of signals, and deconv for division of signals. There are no functions like mult and div.

9. How can the formulation of polynomial be done from its roots?

a) poly, r is a row vector, containing the roots of the polynomial

b) poly

c) poly

d) poly

Answer: b

Explanation: To find the roots, one has to store the given roots in a 1*n column vector, say p, and then extract the co-efficients of the polynomial by typing poly. This would return the co-efficients of the polynomial in descending order from left to right.

10. The function to evaluate the value of a polynomial,l for a constant value of the independent variable in the polynomial is ______

a) poly, p is a row vector

b) polyder

c) polyint

d) polyval, c is a row vector

Answer: d

Explanation: polyderand polyint produces the differentiation and integration of the polynomial p. Polyval is the correct form of the function to evaluate the value of a polynomial whose independent variable is a. The value of a has to be provided first before writing the function.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Managing Variables”.


1. What will be the output when the following code is written in MATLAB?


 u=sin(10);v=pi;whos

a) u and v are double with 8 bytes

b) u and v are symbolic objects

c) error

d) u and v are double arrays

Answer: a

Explanation: ‘sin 10’ and ‘pi’ are numeric values which will be generated as double data type in MATLAB.

Output: Name      Size            Bytes         Class     Attributes

         u        1x1               8           double              

         v        1x1               8           double   

2. What is the disadvantage of the whos function in MATLAB?

a) It does not show the values of the variable

b) It does not show the size of the variable

c) It does not show the class of the variable

d) It does not show the name of the variable

Answer: a

Explanation: whos returns the name, size, bytes and class of the variables used in the current program. To get the value of any variable, we need to type the variable and press Enter.

3. What will be the output of the following code?


A=100; if(A>99) clear A; end

a) A never gets stored in MATLAB

b) A is first stored and then removed from workspace

c) Error

d) A is retained in the workspace

Answer: b

Explanation: A will be stored due to the first line of code. When the if structure is invoked, the variable will be deleted from the program due to the clear function.

4. What is the replacement for the whos function?

a) Workspace window

b) Command window

c) Current folder window

d) Remembering all the variables used

Answer: a

Explanation: The workspace window constantly gets updated with inclusion of any variable in the program. It shows the Value, Size, Bytes, Class and many other attributes of the variables used. Hence it is more useful than the whos function.

5. What does the Workspace show?

a) Attributes of variables, functions from command window

b) Attributes of variables, script files from command window

c) Attributes of variables, script files, functions from command window

d) Attributes of variables from command window

Answer: c

Explanation: The workspace window shows the attributes of variables, script files, functions from the command window for an ongoing program. It is more descriptive than the whos function.

6. What is the output of the following code?


 a=10; b=10; c=’pi’; whos

a) The output will show all double variables

b) The output will show a and b as double and c as symbolic object

c) The output will show a and b as symbolic object and c as char

d) The output will show a and b as double variables and c as char variables

Answer: d

Explanation: ‘a’ and ‘b’ will be stored as double variables with a=10 and b=10 while c will be stored as a character variable as c=pi.

Output:

Name     Size            Bytes    Class     Attributes

  a       1x1              8      double              

  b       1x1              8    double              

  c       1x2              4      char   

7. From the following desktop view of workspace, choose the correct code.

matlab-questions-answers-managing-variables-q7

a) a=10;b=’pi’;syms c; d=[1,2;0;4];

b) a=10;b=’pi’;syms c; d=[1,2;0,4];

c) a=10;b=pi;syms ; d=[1,2;0,4];

d) a=10;b=’pi’;syms c; d=[1,2;0,4];

Answer: a

Explanation: ‘b’ is a character variable, within inverted commas. ‘a’ is a double variable. ‘c’ is a symbolic object while ‘d’ is a 2*2 matrix. The declaration of the variables is in accordance to the following code:

a=10;b=’pi’;syms c; d=[1,2;0;4];

8. What is the size of double and symbolic variables holding integer constants?

a) 8 bytes and 16 bytes

b) 16 bytes and 112 bytes

c) 32 bytes and 26 bytes

d) 23 bytes and 112 bytes

Answer: a

Explanation: The size of double variables holding integer constants is 8 bytes. The size of symbolic variables is 112 bytes. These are predefined data type sizes in MATLAB.

9. Choose the correct option as an inference from the following workspace view.

matlab-questions-answers-managing-variables-q9

a) ‘ans’, ‘p’ and ‘ap’ are double variables

b) ‘ans’ and ‘p’ are double variables while ‘c’ is a character variable

c) ‘ap’ is symbolic object, ‘c’ is a double variable

d) ‘c’ is a symbolic character

Answer: b

Explanation: It is to be noted that ‘ans’ and ‘p’ are double integer variables, ‘c’ is a character variable while ‘ap’ is a symbolic object.

10. What is the difference between who and whos command?

a) The former shows the names of the variables being used while the latter shows the details of the variables in the ongoing program

b) The latter shows the the names of the variables being used while the former shows the details of the variables in the ongoing program

c) No difference at all

d) There is no such function as who and whos

Answer: a

Explanation: The function ‘who’ shows the names of the variables used. The function ‘whos’ shows the details of the variables in the ongoing program but it doesn’t show the attributes of the variables.

11. What is the conclusion from the following code?


 >>whos

 Name     Size         Bytes    Class     Attributes

 ans      1x1            8      double              

 ap       1x1          112  sym              

 c        1x2            4      char

 p        1x1            8      double

a) The function ‘whos’ doesn’t show the values of the variables being used

b) The value of each variable is 0

c) The function ‘who’ is more effective than ‘whos’

d) Nothing can be concluded

Answer: a

Explanation: The function ‘whos’ doesn’t show the values of the variables being used. Instead it will display the size, bytes and class of the variable in use. It is no useful than the function ‘who’ since it only shows the name of the variable used, when invoked.

12. What are Max and Min in the Workspace shown below?

matlab-questions-answers-managing-variables-q12

a) They show the maximum and minimum value of the variable

b) The show the maximum and minimum length of the variable

c) They show the maximum and minimum value present in an array

d) They show the median and mode of the variable

Answer: c

Explanation: The columns ‘Min’ and ‘Max’ show the maximum and minimum values present in a variable. So, if the variable is an array, the ‘Min’ and ‘Max’ may or may not be same. Here, a is a variable having a single constant value so they are same.

13. How would you express a pi as a character and an integer? Choose the correct code.

a) a=pi;b=’pi’;

b) a=22/7; b=pi;

c) a=3.1415; b=22/7;

d) a=3.1429;b=’pi’;

Answer: a

Explanation: After entering the code in MATLAB, the workspace view is:

matlab-questions-answers-managing-variables-q13

A character variable is stored by declaring the character value within a pair of single inverted commas. An integer variable is stored by simply declaring the variable with the integer value. pi is stored in MATLAB as an integer value itself of 3.1416.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Errors in Input – 1”.


1. What will be the output of the following code?


A=sim(pi)+cod(pi)

a) A=-1

b) Undefined function or variable ‘cod’

c) Undefined function or variable ‘sim’

d) Undefined function or variable ‘sim’ and ‘cod’

Answer: c

Explanation: ‘sin’ and ‘cod’ functions have been written in place of ‘sine’ and ‘cos’ functions. If there are more than 1 error in a line of code, MATLAB will return only the first error it comes across. It will neglect the rest of the code. So it ignores the error ‘cod’.

2. What is the output of the following code?


A=[1 2 3]; A^2;

a) [1 4 9]

b) A= 1 4 9

c) A= [1, 4, 9]

d) Inputs must be a scalar or a square matrix

Answer: d

Explanation: Multiplying a column or row vector with a scalar or another vector requires the code to be “A.^2” in place of “A^2”. If this line is replaced, the output will be: A=1 4 9

Output: Inputs must be a scalar and a square matrix.

To compute element wise POWER, use POWER Missing superscript or subscript argument instead.

3. What is the output of the following code?


A=[1 1; 1 1]; A^2

a)


A = 2 2

    2 2

b)


A = 1 1

    1 1

c) Error using ^ To compute element wise POWER, use POWER Missing superscript or subscript argument instead

d) No output

Answer: a

Explanation: ‘A^2’ implies we are multiplying A with A, A being a square matrix. So the answer follows. If the line of code was ‘A.^2’, the answer would be a square matrix, such that a ij =2 of order 2*2.

Output: Cursor shifts to the next line, waiting for a new line of code.

4. What is the output of the following code?


A=[1 2]; B=[1 4]; c=A*B;

a) c= [1 8]

b)


c = 1

    8

c) Inner Matrix dimensions must agree

d) No output since we have closed the line of code with a semicolon

Answer:c

Explanation: Multiplication of two row vectors is possible if we use the ‘.*’ operator. If B was a 1*2 column vector, the multiplication would have been possible resulting in a multiplication of vectors and generating c=9 as output.

5. What is the output of the following line of code?


t=0:pi/8:4pi;

a) No output as we’ve closed the line of code with a semi-colon

b)


1      2        3        4        5        6        7       8        9

0    1.5708   3.1416   4.7124   6.2832   7.8540   9.4248  10.9956  12.5664

c) Error: Unexpected MATLAB expression

d) Undefined function or variable ‘pi’

Answer: c

Explanation: Multiplying an integer with a variable which contains a constant value requires the use of ‘*’. So 4pi should be ‘4*pi’. ‘pi’ is predefined in MATLAB as 3.1416.

6. What is the error in the code?


a=[[1;2];(2,3)]

a) Third brackets are wrong

b) The semicolon within the second third brackets

c) There is no error

d) Error: Expression or statement is incorrect–possibly unbalanced

Answer: d

Explanation: A matrix cannot have parentheses within itself. Any integer, whether to be included row wise or column wise, is to be written within a third bracket.

7. What is the output in the following code?


a=[[1;22],[53;9],[13;2]];

a) There is no output

b) Columns are to be introduced by placing semi-columns

c) Dimensions of matrices being concatenated are not consistent

d)


a = 1    53    13

   22     9     2

Answer: a

Explanation: The a matrix will be stored in the workspace as

a = 1    53    13

   22     9     2

There is no error and there will be no output since the dimensions of matrices being concatenated are constant.



8. What is the difference between the two codes?


a> P=[91,’pi’];

b> Q=[91,pi];

a) Code a initialises P as a character array while code b initialises Q as an integer array

b) Both P and Q will be integer arrays

c) Code b initialises P as a character array while code a initialises Q as an integer array

d) Both P and Q will be character arrays

Answer: a

Explanation: One should keep in mind that once while declaring a vector, a character is introduced with a pair of single-inverted commas, the vector becomes a character array. So it will show different answers while doing algebraic operations on it.

Output:

For a>   P= [pi

    b>   Q= 91  3.1416

9. What is the output of the following code?


P=tan90

a) Inf

b) P = Inf

c) P = -1.9952

d) Undefined function or variable ‘tan90’

Answer: d

Explanation: To evaluate numerical value of any trigonometric expression, the angles should be placed within a pair of parentheses. That’s why the above code generates an output.

10. What is the output for the following code?


if(a>b) p=9;

a) No output

b) Never will there be an output

c) a, b, p are not initialized

d) p=9

Answer: b

Explanation: Any control structure or loop structure has to be terminated with the code ‘end’. Else the cursor will keep on demanding further lines of codes. This is why, for the above code, the output will never appear.

11. What is the output of the following code?


P=sin[90];

a) P = 1

b) P = .8932

c) P = .99999

d) Error

Answer: d

Explanation: The input to the sin command has to be within parentheses. Since the input is given within [], it leads to an error.

12. What is the output of the following code?


system(cmd)

a) Opens command prompt

b) Opens command prompt in a separate window

c) Opens command prompt in MATLAB

d) Error

Answer: d

Explanation: The input to the system command has to be within ‘’. Since, the cmd command has been written without it, it leads to an error.

13. Why is the output, as shown, ‘poe’?


>>clipboard(‘paste’, ‘Do re Mi fa’)

ans =

      ‘poe’

a) ‘poe’ was initially in the clipboard

b) Cannot be determined

c) Error

d) The text gets changed

Answer: a

Explanation: If we’ve used the clipboard command to copy a string before, we need to paste it already. We cannot use the ‘paste’ keyword to paste a new string if there’s already a string in our clipboard.

14. What is the output of the following code?


clipboard('cut','Do re Mi fa')

a) Error due to syntax

b) Error due to command

c) Error due to cut

d) Cuts the portion of a text where ‘Do re Mi fa’ is written

Answer: c

Explanation: The clipboard command allows the user to only copy and paste. Hence, we get an error. It can’t be used to cut a portion of a text.

This set of MATLAB Questions and Answers for Freshers focuses on “Errors in Input – 2”.


1. What is the output of the following code?


isvector((49 32));

a) Error in 

b) Error due to absence of comma

c) Error due to command

d) Logical 1

Answer: a

Explanation: The input to the command isvector should be placed within [] always. If the input is a single element, it can be placed within . But since there are two elements, the above code will give an error.

2. What is the output of the following code?


clipboard('Do re Mi fa','copy')

a) Error in hierarchy

b) Copies the input text to the system clipboard

c) Replaces any text, in the clipboard, with the input text

d) Syntactical Error

Answer: a

Explanation: The ‘copy’ input should be before the text which we want to copy to our system clipboard. Since it has been placed after the text, we get an error.

3. What is the output of the following code?


commandhistory[]

a) Error

b) Shows command history

c) Shows the previous command used

d) Prints all the commands used for the current session

Answer: a

Explanation: We cannot give [] after the following command. We may give parentheses but it’s not needed though. Here, the output will be an error eventually.

4. What is the output of the following code?


pd=makedist('Uniform','Lower',3)

a) Error in giving limits

b) A uniform distribution with lower limit 3 and upper limit Infinity

c) Error in syntax

d) Error due to the command

Answer: a

Explanation: The default limit, if a limit isn’t mentioned are, 0 for lower limit and 1 for upper. Here, we’ve only mentioned the lower limit as 3 and the upper limit gets initialized as 0. This causes a typical error since there can’t be a uniform distribution whose lower limits is greater than the upper limit.

5. What is the output of the following code?


p=input('');

po

a) ‘po’ gets assigned to p

b) Error in the input

c) Error due to syntax

d) Cannot be determined

Answer: b

Explanation: The given input, po, results in an error. If after the input command, we want to give a text input, we need to include the input within ‘’. Since we’ve not given po within ‘’, it results in an error.

6. What is the output of the following code?


p=input[''];

a) Asks for an input

b) Error in the input

c) Error due to syntax

d) Cannot be determined

Answer: c

Explanation: There is a syntactical error in the above code. This is because we’ve given [] after the input command but the syntax of the input command requires us to put parentheses after it. This leads to an error.

7. What is the output of the following code?


pd=makedist('Uniform','-Inf',lower,'Inf',upper)

a) Makes a uniform distribution ranging from -Inf to Inf

b) Error due to Inf

c) Error due to syntax

d) Logical Error

Answer: c

Explanation: Before mentioning the lower limit for the uniform distribution, we need to mention ‘lower’. Even though we will receive an error, due to Inf, if the aforementioned syntax is followed- that will be the 2 nd error MATLAB observes while the first error is the fact that lower is mentioned after defining the lower limit. This leads to an error.

8. What is the output of the following code?


sumsqr([1 2; 'NaN' 4])

a) 21

b) Error due to NaN

c) Error due to ‘NaN’

d) 9

Answer: c

Explanation: When we write NaN within ‘’, we declare it as a character. Now, the sumsqr command can only take integers as input. Since there is a character0 it results in an error. Hence, the output is option c and not b. If it was not placed within ‘’, it would’ve been ignored and the output would’ve been 21.

9. The uniform distribution can range from -infinity to 0 or 0 to Infinity but not from -infinity to infinity.

a) True

b) False

Answer: b

Explanation: The uniform distribution can typically range from , i.e. the lower and upper limits of the distribution cannot be less than or -Infinity or more than Infinity respectively. Hence, this leads to an error.

10. If a character input is given to a command which only takes integers, it’ll always give an error.

a) True

b) False

Answer: a

Explanation: MATLAB is very sensitive to the nature of inputs defined for a particular command. If the input to a command has to be an integer but we give a character input, it’ll give an error.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Variables and Assignments”.


1. Which function is preferable to find the magnitude of a complex number?

a) abs

b) sqrt

c) cart2pol

d) MATLAB does not support complex arguments

Answer: a

Explanation: In the function sqrt, we have to write the polynomial which shows the sum of squares of the real and imaginary part within the parentheses. But in abs, we only have to enter the variable which we’ve used to define the complex number. So abs is more preferred.

2. Which is an escape sequence constant?

a) Esc

b) /n

c) \b

d) nargout

Answer: c

Explanation: An escape sequence character constant is used in functions which are used to show output. ‘\b’ means backspace. ‘Esc’,‘/n’, are strings. ‘nargout’ is a pre-defined function in MATLAB.

3. All MATLAB computations are done in

a) Single Precision

b) Double Precision

c) Linear accuracy

d) Multi-level precision

Answer: b

Explanation: MATLAB stores any integer variable as a double data type of 64 bits. For single precision, the function is ‘single’ but if not mentioned, the value will be stored in double precision.

4. Which symbol is used to initialise a variable?

a) =

b) ->

c) ==

d) init

Answer: a

Explanation: The symbol, ‘=’, is used to initialise a variable with a particular data type. ‘==’ checks whether the left hand side is equal to its’ right hand side. ‘init’ is a separate function in MATLAB.

5. Choose the correct option.

a) any shows all the elements in a matrix while all shows every element of a vector

b) any is ‘true’ if elements in a vector is zero

c) all is ‘true’ if every element in a vector is non zero

d) all is ‘true’ if every element in a vector is 0

Answer: c

Explanation: ‘any’ and ‘all’ are pre-defined functions in MATLAB. The function ‘any’ returns 1 if every element of the vector, mentioned within the parentheses, is non-zero. The function ‘all’ returns 1 if any element of the vector is non-zero.

6. What operator helps in the transpose of a matrix?

a) “ .’ ”

b) “ ‘ ”

c) “./ ”

d) “ .\ ”

Answer: a

Explanation: ‘ .’ ‘ is used to get the transpose of a matrix. ‘ ‘ ‘ is used to get the complex conjugate transpose of a matrix. ‘ ./ ’ is used for the right division while the operator, ‘ .\’ is used for left division.

7. What is the difference between the expressions  & ?

a) Computational difference

b) Final results are different

c) No difference

d) Cannot be determined

Answer: a

Explanation: MATLAB follows a precedence of operators while doing any computation. So  is done like this: 9*1-8=9-8=9. But  is done like this: 9-1*8=9-8=1. Even though the answers are same, there is a computational difference between evaluation of the two expressions in MATLAB.

8. What is the output of the expression


(2*9*Inf)+(9-1*Inf)

a) Inf

b) Error

c) Incomprehensible

d) NaN

Answer: d

Explanation: ‘NaN’ is a pre-defined variable in MATLAB. Whenever we try to evaluate an expression, if the expression contains sub-expressions which evaluate to infinity, the output produced is NaN. This denotes that the evaluation will not lead to number comprehensible by MATLAB.

9. The expression cos is equal to1 in MATLAB.

a) True

b) False

Answer: b

Explanation: Any argument within the parentheses of the functions ‘sin’, ‘cos’ are taken to be in radians. If the argument is to be processed in degrees, the function is modified as sind and cosd.

10. Evaluate the expression:


a=9/1*5/1;  b=a*a/a*a; c=sind(30)+1/2;  d=1-c; e=a+b*c-d

a) 2045

b) 2070

c) Error since sind is a wrong function

d) 0

Answer: b

Explanation: Following precedence of operators: ‘*’ > ’/’ > ‘+’ > ’–‘

a=9*5=45 ; b=a 2 /a*a=a*a=a 2 =2025 ; c=1/2+1/2=1 ; d=1-c=0 ;

e=45+2025*1-0=45+2025-0=2070-0=2070.

Output: 2070

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Solving Equations”.


1. What is the syntax to solve simultaneous equations easily?

a) solve[“equation-1”,”equation-2”];

b) sol[“equation-1” “equation-2”];

c) sol[‘equation-1’‘equation-2’];

d) solve[‘equation-1’,‘equation-2’];

Answer: d

Explanation: To solve equations simultaneously, we need to place the equations within the pre-defined MATLAB function ‘solve’ as string arguments within a pair of single inverted commas and separated by a comma. The function sol can also be used but the syntax within the third bracket is same. So, solve[‘equation-1’,‘equation-2’]; is correct.

2. An employer has to minimize the number of lines in a program while writing the code for a purpose. If the purpose is to find the root of the following equation, which function is to be used?


x2-4x+3=0

a) polyval

b) solve[]

c) sol[]

d) roots

Answer: d

Explanation: The function polyval returns the value of a dependent variable by taking arguments of the independent variable. ‘sol[]’ returns the values in a vector form but does not display the exact values. If we use ‘solve[]’, we have to write the entire equation in a string. ‘roots’ allows the user to only insert the coefficients of the polynomial and it will return the roots of the equation formed by the coefficients entered.

Output: roots([1 -4 3]

ans=1

    3

3. What is the difference between sqrt and sqrt)?

a) There is no difference

b) sqrt) is incorrect

c) There is no function as sqrt

d) sqrt returns exact value while sqrt) returns 10 

Answer: d

Explanation: ‘sqrt’ is a predefined function used to find a square root of large numbers to reduce the complexity of equation. sqrt) introduces 10 as a symbolic object to the MATLAB workspace.

Thus it will return 10  as a symbolic expression and won’t divulge the exact root. This helps often to reduce an equation before increasing program complexity in MATLAB.

4. The solve[] command can do which of the following things?

a) Produce the exact solution

b) Produce a symbolic solution

c) Produces exact roots

d) Produces complex roots

Answer: b

Explanation: The solve[] function is an inbuilt function to generate the solutions of one or more than one equations. But the result is always produced in symbolic form. So, even if the answer contains the value of square root of 5, solve[] will return the value as sqrt).

5. What should be the output for the following code?


t=linspace(0,10);fzero(inline('t+t2'), 5);

a) Nan

b) -0.000000000000000000000000117191203927370461282452866337

c) -1.1719e-25

d) fzero is not a function

Answer: a

Explanation: While introducing the function within fzero, there should be a zero crossing point near the value where we expect a solution. But in the above code, it is observable that there are no zero crossing points near 5. Thus MATLAB will return an error in computation which is a NaN value that has disrupted the process of the function fzero.

6. A student has to find the solution of an equation cos=1/2. She has to write the program such that exact values are shown at output. Which of the following codes would help her?

a) syms x;eqn = cos == 1/2;vpa)

b) syms x;eqn = cos == 1/2;solve

c) vpa=1/2’))

d) syms x;eqn = cos = 1/2;vpa)

Answer: c

Explanation: To find the exact value of non-integer constants, we use the function ‘vpa’. MATLAB won’t understand sin=1 as an equation until we initialise x as a symbolic variable. syms x;eqn = cos == 1/2;vpa) would’ve generated the same answer but it has 3 lines while vpa=1/2’)) has only 1 line. Once we introduce the variable x as a string, MATLAB understands that it is a symbolic object.

Output: syms x;eqn = cos(x) == 1/2;vpa( solve(eqn,x))

       ans = -1.0471975511965977461542144610932

              1.0471975511965977461542144610932

7. Find the error in the following code?


Predicted output: (b + (b2 - 4*a*c)(1/2))/(2*a)

     (b - (b2 - 4*a*c)(1/2))/(2*a)

Code: solve (b*x2 + c*x + a == 0)

Present output: -(c + (c2 - 4*a*b)(1/2))/(2*b)

  -(c - (c2 - 4*a*b)(1/2))/(2*b)

a) Predicted output is same as present output after math magic

b) solve(a*x 2 + b*x + c == 0)

c) vpa(solve(a*x 2 – b*x + c == 0))

d) solve(a*x 2 – b*x + c == 0)

Answer: d

Explanation: MATLAB returns variables in the order we enter them. Now, both option (a*x 2 + b*x + c == 0) and (a*x 2 – b*x + c == 0) are okay but the predicted output is returned in symbolic form. We see that 1 ⁄ 2 is written as 0.5. Thus vpa is not to be written in the line of code, since it returns exact values and not symbolic values.

8. Which program can help to solve the following differential equation?


dy/dx=b*y     y(0)=5;

a) syms y a;equn = diff==b*y;cnd=y==5;ySol=dsolve

b) syms y a;eqn = diff == a*y;ySol = dsolve=5);

c) syms y a;eqn=diff=a*y;cond=y==5 sol=dsolve;

d) sym y a; eqn=diff==a*y;cond=y==5;sol;

Answer: a

Explanation: To solve an ordinary differential equation using MATLAB, we use the syntax dsolve. The cond variable has to be written in the format ‘cond= indep variable== conditional value. This cond has to be predefined before applying it in the dsolve function.

9. What happens if dsolve does not return any numerical solution?

a) The equations have no solution

b) The equations have a trivial solution

c) The equations have infinite no. of solutions

d) The equation has to be solve separately

Answer: d

Explanation: We have to solve the differentiation numerically. To do it in MATLAB, we need to use ode45 after converting the differential equation to a system of first order differential equation.

10. If solve does not return any solution, what does it imply?

a) The equation has no definite solution

b) The equation has a solution for a specific interval

c) The equation may be solvable but the function ‘solve’ cannot produce a solution

d) There is no function ‘solve’

Answer: c

Explanation: It may so happen that an equation may not be solvable but due to some mistake, the function solve0 has encountered an argument which is an equation whose Left hand side could never be equal to the right hand side. It may also happen that some separate solution is present but the function cannot produce the solutions. We need to check separately for such cases by applying some other methods of solving equations though, generally, this does not happen.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Vectors and Matrices – 1”.


1. Vectors depend upon brackets while scalars don’t.

a) True

b) False

Answer: a

Explanation: To declare a scalar, we only need to declare a variable in MATLAB with a constant expression. We don’t need to include the expression with any kind of brackets. But, we need to put the expressions within a bracket for row or column vector.

2. How many errors will MATLAB show if the following code entered?


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

a) 2

b) 1

c) No error

d) 4

Answer: b

Explanation: There are two errors here. Firstly, vector dimensions should be the same for A and B to compute the C matrix. Secondly, vector multiplication is done by the symbol ‘.*’. So, D=C*A will give an error but MATLAB as soon as it encounters the first error, it will stop compiling the code and return the first error invoked. Hence the number of errors MATLAB will show is 1.

3. To see the sub-matrix with a ij for 2<=i<=4 and 1<=j<=2 of a matrix a, of order 5*6, which code is used?

a) a

b) a

c) a

d) a

Answer: c

Explanation: To see the sub-matrix of a matrix a, of any order , the following syntax is used: matrix name. Here, ‘2:4’ mentions rows from 2 to 4 while ‘1:2’ mentions the columns from 1 to 2. This is a pre-defined form of viewing or making a sub-matrix of a matrix in MATLAB.

4. Which code shows the use of ellipsis in MATLAB?

a)


  A = [1 2 3;...

      5 6 7]

b) A = [1;2’3]

c)


   A = [1;2..

        3;4]

d) A = [1:2..:2]

Answer: a

Explanation: Ellipsis is a method of continuing lines in MATLAB to fit in a matrix if the length is very big to be in a row. The correct syntax for ellipsis while other options will generate an error of invalid input character and unexpected MATLAB operator respectively.

  A = [1 2 3;...

      5 6 7]

It is another form of continuing lines but that form is called carriage return.


5. What is the symbol used to evaluate the transpose of a vector?

a) “ ^ ”

b) “ * ”

c) “ ‘ ”

d) “ ~ ”

Answer: c

Explanation: It is pre-defined in MATLAB that if we want to find the transpose of a vector, we will have to use the “ ‘ ” symbol following the vector or the vector name. “ ^ ” is used to raise the power of a variable while “ * ” is used for multiplication purposes. “ ~ ” is used to denote not-equal to the operator which is “ !~ ”. Hence option “ ‘ ” is correct.

6. What is the advantage of MATLAB over other computing software with matrix dimensions?

a) No advantage

b) Real time pre-defined memory allocation

c) Real time user-defined memory allocation

d) Matrix operations are easily computed

Answer: c

Explanation: In many softwares, while declaring a matrix- the user has to assign a size of the matrix before entering any values to it. But in MATLAB, the user does not need to mention any size; mentioning the number of elements is enough for MATLAB to determine the size of the matrix required.

7. Which code will help to concatenate two matrices easily in 2 dimensions?


Matrices:   A = 1 2 B = 1 2

        3 4         3 4

a) cat

b) cat

c) cat

d) cat

Answer: b

Explanation: The syntax to concatenate two matrices along a specific dimension, d, is cat. Now, we don’t have to define the two matrices explicitly if we don’t need to. We can enter the matrices, within the cat, as we declare a matrix. MATLAB would check for the syntax of matrix declaration and concatenate the matrices. To declare matrix A, the code is A=[1 2;3 4] where a “;” signifies an increase in rows- same goes for declaring B.

8. Which code can be used for changing the dimensions of a matrix as follows?


Input matrix: 1     2     3 Output matrix: 1 4 2 5 3 6

        4     5     6

a) reshape

b) reshape

c) reshape

d) reshape

Answer: a

Explanation: There is a pre-defined function in MATLAB which allows the user to change the dimensions of a matrix without much to be done. The function is ‘reshape’ where A is the original matrix, row denotes desired rows while column denotes desired columns. Now, the matrix A is defined in MATLAB as A=[1,2,3;4,5,6], but we don’t need to do it explicitly. We can put it directly within the function and henceforth put the desired row and columns required.

9. What is the function used to multiply a matrix, A, with itself n times?

a) mtimes

b) ntimes

c) mtimes

d) mtimes

Answer: a

Explanation: The syntax of the function to multiply a matrix with itself n times is ‘mtimes; where A is the matrix itself and n is the number of times the matrix need to be multiplied to itself. There are no function ntimes in MATLAB and the rest of the options show incorrect syntax.

10. Which code is used to solve the system of linear equation: A.(x 2 )= B?


A = 1 4 B = 1 2

    1 4     1 2

a) sqrt

b) Inf

c) sqrt

d) sqrt[]

Answer: a

Explanation: It is seen from the equation that if we divide B by A and find the square root of the result, we will get the values of x in a vectored form. But, the matrices are singular matrices. So determinant value of both matrices is 0. Hence the output will be as follows

Output:    ans=

      0.0000 +    Infi      Inf + 0.0000i

        0.0000 +    Infi      Inf + 0.0000i

11. Which operator set is used for left and right division respectively?

a) .\ and ./

b) ./ and .\

c) Left division and right division is not available in MATLAB

d) / and \

Answer: a

Explanation: In MATLAB, if we want to perform left division of two matrices we need to write a.\b while for the right division we have to write a./b. for left division respectively.

12. If A and B are two matrices, such that a./b=b.\a, what is concluded?

a) Nothing special

b) A = A T

c) A = A -1

d) A = A

Answer: a

Explanation: a./b is same as b.\a. In the former, we are performing left division so b is divided by a. In the latter, we are performing right division so b is again divided by a. Thus, it is obligatory that a./b=b.\a. Hence, nothing special can be said about the two matrices A and B.

13. If a./b= T , what can be concluded about the matrices a and b?

a) a = b T

b) a = b -1

c) a = b’

d) nothing special

Answer: a

Explanation: ‘a./b’ means that elements of a are divided b while ‘b./a’ means that the elements of b are divided by a. If the result of the latter is the transpose of the former, it suggests that a=b T . This is because element-wise division is performed by the operator ‘./’. So the resultant matrix is a direct symbolisation of the nature of occurrence of elements in either matrix. Hence option a=b T is correct.

14. What is the difference between a[] and a{}?

a) a[] is for empty cell array while a{} is for empty linear array

b) a[] is for empty linear array while a{} is for empty cell array

c) No difference

d) a[] is an empty row vector while a{} is an empty column vector

Answer: b

Explanation: To initialise a cell array, named a, we use the syntax ‘a{}’. If we need to initialise a linear array, named a, we use the syntax ‘a[]’. This is pre-defined in MATLAB.

15. Choose the function to solve the following problem, symbolically, in the easiest way.


3x+y=5 and 2x+3y=7

a) linsolve where x and y are the co-efficient and result matrix respectively

b) solve where x and y are the co-efficient and result matrix respectively

c) sol where x and y are the co-efficient and result matrix respectively

d) the equations are not solvable

Answer: a

Explanation: ‘linsolve’ performs LU factorization method to find the solution of a system of equation AX=B. The syntax is ‘linsolve’ where x is the co-efficient matrix while b is the result matrix. The function solve  could’ve been used, but the expressions within parentheses should be the equations, within apostrophes, declared as strings. Same for sol. Hence, option linsolve where x and y are the co-efficient and result matrix respectively is correct.

Output: linsolve([3,1;2,3],[5;7]

  ans=

  1.1428571428571428571428571428571

        1.5714285714285714285714285714286

This set of MATLAB Interview Questions and Answers for freshers focuses on “Vectors and Matrices – 2”.


1. What is the output of the following code?


A=[1 2 3..

        ];

a) The output is suppressed

b) A row vector

c) A row vector concatenated with a null matrix

d) Error

Answer: d

Explanation: The above code will give in an error due to the fact that ellipsis hasn’t been done properly. There should’ve been a semi-colon after 3 and we need to give 3 dots. Thereafter, option “the output is suppressed” is actually correct because the output would essentially be suppressed while a row vector A gets stored in the workspace.

2. What is the output of the following code?


A=[1 2 a..;

         ];

a) Error due to a

b) Error due to A

c) Error due to [];

d) Error due to ;

Answer: a

Explanation: Typically, the row vector A contains integers as the first element and thus the entire array becomes an integer vector. But the inclusion of a results in an error since a is a character. If, however, a was written within ‘’, there wouldn’t have been a error.

3. What is the output of the following code?


A=[1 2 ‘a’;…

          ];

a) Error due to ‘a’

b) Error due to ‘…’

c) Error due to []

d) ‘a’

Answer: d

Explanation: MATLAB would show such kind of an output since the A vector gets defined as a character array when a gets defined within ‘’. The syntax for ellipsis is correct and there is no error.

Output: ‘a’

4. What is the output of the following code?


A=[1 2 ‘a’;…

  ‘f’ ‘q’ ‘w’];

a) A 2*3 character array

b) A 3*2 character matrix

c) A 3*2 character vector

d) A 2*3 character vector

Answer: b

Explanation: The above code performs ellipsis to concatenate two matrices vertically. Thus, the output is a 2*3 matrix since the dimension of each vector, it concatenates, is 3. Now, the presence of a character makes the vector character vectors.

5. What is the output of the following code?


A=[1 2 ‘a’;…

   ‘f’ ‘q’ ‘w’;…

   ]];

a) Syntax Error

b) A 2*3 character matrix

c) The concatenation of 2 vectors, vertically, with size 3

d) Cannot be determined

Answer: a

Explanation: There are two ]] at the end. This leads to an error. This is because only one ] was sufficient to produce A as defined in the option concatenation of 2 vectors, vertically, with size 3. But the usage of an extra ] leads to an error the code.

6. What is the output of the following code?


A=[1 2 ‘a’…;

   ‘a’ ‘b’ ‘c’;…

           ];

a) Error in syntax

b) A 3*2 matrix of characters

c) Error due to 1 and 2

d) Error due to a

Answer: a

Explanation: Ellipsis has been written wrong in the first line. This is because there has to be 4 ‘.’ for concatenating vectors row-wise. Since we’ve not used 4 dots, it leads to an error.

7. What is the output of the following code?


A=[1 2 ‘a’….;

‘a’ ‘b’ ‘c’;…

           ];

a) A 1*6 matrix

b) A 6*1 matrix

c) Error in the code

d) Error in ellipsis

Answer: a

Explanation: In the above code, ellipsis is done to concatenate two vectors row-wise. There is no error in the syntax ad the output A 1*6 matrix.

8. What is the output of the following code?


clear ALL 

a) Clears the workspace

b) Clears the matrices

c) Clears the vectors

d) Clears ALL

Answer: d

Explanation: The following code clears the variable ALL from the workspace. Notice that it won’t give an error even if the ALL variable is not present in the workspace. The correct option is Clears ALL.

9. All matrices are vectors but all vectors are not matrices in MATLAB.

a) True

b) False

Answer: a

Explanation: If a=[], a is a matrix but not a vector in MATLAB. Hence, the above statement is true.

10. What is the output of the following code?


ismatrix([]);

a) logical 1

b) logical 0

c) logical -1

d) Error

Answer: a

Explanation: The ismatrix(0 function returns a logical 1 if the size of the input vector is [m,n] where m,n is non-negative. This is important to remember. The size of [] is 0*0 which is non-negative. Hence, the output is 1.

11. What is the output of the following code?


isvector([]);

a) 1

b) 0

c) Syntactical error

d) Logical error

Answer: b

Explanation: The isvector command typically would return a 0 is the input is a null vector. Hence, the output of the above code is 0.

12. If the dimensions of vectors don’t match, the plot command will always give an error.

a) True

b) False

Answer: b

Explanation: In the following case: plot, the plot command takes x as [a-1:.2:a+1]. Hence, the above statement is not true. A graph will eventually get plotted.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Functions”.


1. What is the name of a primary function?

a) Name of M-file

b) Name of Script File

c) Name of Help file

d) Name of Private-File

Answer: a

Explanation: M-files are text files which can be created in any text editor and it contains the description of a program written for a particular purpose. The program description is mainly a self-contained set of statements which comprises of lines of codes or different kinds of functions. Thus the name of the primary function, where the program description is described, is the M-file.

2. Predominantly, what are the two kinds of errors in MATLAB programs?

a) Syntax and runtime

b) Syntax and logic

c) Logic and runtime

d) Syntax and algorithmic

Answer: a

Explanation: Usually, there are two kinds of errors in any programming language. They are syntactical errors and runtime errors. Syntactical errors arise due to the programmer not following language specific syntaxes. Runtime errors rise due to faulty logic decided for the program, the error is called Runtime error.

3. Which code would you use to find the value of the function f?


f(x)=sin(x) + cos (x) + tan (x) at x = π/4

a) sin+cos+tan

b) sin+cos+tan

c) sin+cos+sin

d) sind+cosd+tand

Answer: d

Explanation: sin would return 0.8509 and sin would return 0.7071. They won’t return exact value of sin 45®. But sind will return 1, this is a pre-defined function in MATLAB. The same goes for cosd and tand.

4. If the program demands evaluation of multiple, only decimal, values of the same function, what is the better way amongst the following?

a) Using anonymous functions or inline functions

b) Using str2func

c) Using private functions

d) Using any function

Answer: b

Explanation: The function str2cat returns floating point or decimal expressions for integer values or fractional values. Anonymous functions and inline return decimal values for fractional values but not for integer values. Hence, str2cat is preferable.

5. What are persistent variables?

a) Variables which retain values between calls to the function

b) Variables which help in calling a function

c) Variables which deal with functions

d) Variables global to the function

Answer: a

Explanation: Persistent variables help to retain the value which has been produced by a sub-function. They are local to the sub-function but MATLAB reserves permanent storage for them so they might seem like global variables. They are never shown in the workspace so they differ from global variables.

6. Variables need to have same name while being passed from the primary function to the sub-function.

a) True

b) False

Answer: b

Explanation: It is dependent upon the programmer to choose the variable name while establishing a connection between a global and a persistent variable. Essentially, one may choose to keep the variable name same to avoid confusion in case of multiple sub-functions. But it is not necessary if there are a small number of sub-functions.

7. Find the error in below code.


>>f = inline('t.^4', 't'); g = inline('int(h(t), t)', 't');

a) There is no function as inline

b) The error will be in defining g

c) The error will be in evaluating a numeric value for the function g

d) Syntactical error in defining g

Answer: d

Explanation: While defining an expression using the function inline, the input string argument placed within a pair of apostrophe has to contain characters or variables along with arithmetic or logical operator. The function ‘int’ will evaluate the integration of the function h. So the error will be in introducing the function h within the string input.

8. Which command can be used for single step execution in debugging mode?

a) dbstep

b) dbstepin

c) dbstatus

d) dbcont

Answer: a

Explanation: The function ‘dbstep’ helps in single step execution while ‘dpstepin’ helps to enter into a function. The function ‘dbstatus’ helps to list all the breakpoints in a function while ‘dbcont’ helps to continue execution. These are the pre-defined debugging commands in MATLAB.

9. How do we access a global variable in nested functions?

a) Simply seek the variable from the primary function

b) Make a copy of the global variables from the primary function

c) Declare the variable within the function

d) Declare the variable as global

Answer: d

Explanation: Any global variable, in the primary function, if required to be accessed by a nested function- the variable needs to be declared with the global keyword within the function which requires access to it. This allows sharing the variable amongst the primary and other functions. If the variable is declared without using the global keyword, the variable might bring an error to the function.

10. How does MATLAB help in passing function arguments?

a) By call by value and call by reference

b) Only by call by value

c) Only by call by reference

d) By call by address

Answer: a

Explanation: Like C, MATLAB allows to pass almost all arguments by value. But, if the argument passed into the function is only for mathematical purpose then it is passed as a reference. This helps in saving the memory reserved for the original value of the argument.

11. Which line is treated as H1 line?

a) Comment line succeeding function definition

b) Comment line preceding function definition

c) Comment line after function

d) All lines before and after function definition

Answer: c

Explanation: When we have many functions nested in a primary function, it is a good practice to place comment lines which would help anybody to understand the purpose of the function- making the function more versatile. This comment line introduced right after the function definition is treated as H1 line. All other comment lines after or preceding the function definition won’t be returned as H1 line when the H1 line is sought in MATLAB.

12. Find the error returned by MATLAB:


syms a x y; a = xˆ2 + yˆ2;    subs(a, [x,y], (2,3,4))

a) There is no subs command in MATLAB

b) The subs command has syntactical error

c) The subs command has extra input arguments

d) The subs command has incorrect arguments

Answer: b

Explanation: If we want to substitute the variable with constants to get the value of ‘a’, we will have to introduce the constants within third brackets. The subs command is pre-defined in MATLAB and hence MATLAB will produce a syntactical error. It shows the first error it sees while compiling our code so it won’t show that the subs command has extra input arguments.

13. Predict the error, MATLAB will generate, in the following line of code:


 g = inline(‘3x+5*x’, ‘t’)

a) No error

b) Syntactical error

c) Wrong arguments

d) Expecting (,{ or [

Answer: a

Explanation: MATLAB will generate no error. But if we try to find an integral value of the function defined within the string argument, MATLAB will generate an error saying the variable t is defined. This is because we have used ‘x’ as the only variable within the string input. We can change‘t’ to ‘x’ or change the variable ‘x’ in the string input to ‘t’.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Graphics”.


1. What are the functions to see the graph of a continuous and a discrete function?

a) plot & stem

b) cont & disc

c) plot & disc

d) cont & stem

Answer: a

Explanation: The pre-defined function in MATLAB to view the graph of a continuous and discrete functions is plot and stem respectively. There is no such function as cont or disc.

2. Find the error in the following code.


x=-10:1:10; y=-10:2:10; plot(x,y)

a) Plot is not available in MATLAB

b) Syntax of plot is wrong

c) Length of x and y should be same

d) No error

Answer: c

Explanation: It is highly important that the length of the variables, between which we need to plot a graph, be same. This is a pre-defined syntax of MATLAB so MATLAB will return an error if the lengths are not same.

3. What is the output in the following code?


x=-10:1:10; y=-10:1:10;axis(‘off’); plot(x,y)

a) Error

b) A graph will be shown without axes

c) A graph will be shown with axes

d) 2 graphs will be shown- one with axes and with no axes

Answer: c

Explanation: We have used the axis command before the plot command. So, the plot hasn’t been created before the axis command is invoked. Hence a graph of x and y will be shown which will have axes.

4. If we want to plot matrix arguments, which of the following gets plotted?

a) Column wise inter-relation of two arguments

b) Row wise inter-relation of two arguments

c) Diagonally inter-relation of two arguments

d) The arguments are incomprehensible

Answer: a

Explanation: We have to keep in mind the order while trying to plot two matrix arguments. MATLAB will take the column wise relation between the two arguments.

So, if x=[x1 x2 x3];y=[y1 y2 y3]; plot- MATLAB will generate a plot between , and so on.

5. To bring the scale of each axis to logarithmically spaced, the student entered ‘semilogx’. What really happened?

a) The plot will appear with both axis now logarithmically spaced

b) semilogx is an invalid function

c) The plot will appear with x axis logarithmically spaced

d) Error

Answer: c

Explanation: semilogx is a pre-defined logarithmic plot function in MATLAB. It will help to bring down the scale of the x axis in out plot to logarithmically spaced values.

6. What kind of a plot is this?

matlab-questions-answers-graphics-q6

a) Polar plot

b) Cartesian plot

c) Complex plot

d) Not a MATLAB plotting

Answer: a

Explanation: MATLAB generates a polar plot to represent the polar co-ordinates of a trigonometric function. This is done with the help of the function ‘polar’. The angle increases in the anti-clockwise direction.

7. After trying to plot a pie-chart, the student finds that the function he used is rose. What is the nature of data used by the student if an output graph is generated?

a) Angles in radians

b) Linear bivariate

c) Logarithmic

d) This is not possible in MATLAB

Answer: b

Explanation: The student gets an angle histogram plot. So, he used the wrong function. But the plot was generated. So, his lines of code have defined the date in terms of angles. Plus he has used the rose command in place of the pie command.

8. To place a text on the plot using a mouse, the command used is _________

a) gtext

b) text

c) title

d) atext

Answer: a

Explanation: This is a pre-defined function in MATLAB. If we want to place a text at a position, of our interest, in a graph- we need to use the gtext command.

9. What is the condition on x in bar?

a) No condition as such

b) Should change linearly

c) Should increase of decrease monotonously

d) Incomprehensible

Answer: c

Explanation: The values of x should be increasing monotonously or decreasing monotonously. This is due to the fact that each argument in x refers to the particular position of a bar in the bar plot.

10. If we put bar, we will get _____ bars.

a) Uniform

b) Damped

c) Overlapping

d) No

Answer: c

Explanation: Usually, the default value of width is 0.8 for the function ‘bar’. Now, if we increase bar width to a value more than 1, the bars would overlap on each other- resulting in a bar plot of overlapping bars.

11. A student has to plot a graph of f=t and g=t in the same graph, with t as a parameter. The function he uses is ____

a) plot3

b) plot

c) disp

d) stem

Answer: a

Explanation: The function to be used is plot3. This will allow him to draw a 3d plot as asked. The plot will show both the functions ‘f’ and ‘g’ with t on the z-axis.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Statistics”.


1. To exhibit time-series or spatial-series data, what kind of diagrams are suitable?

a) Pie-bar

b) Pie-chart

c) Ratio-chart

d) Bar-diagram

Answer: d

Explanation: Time-series or spatial-series data would comprise of quantitative characters. So they can be represented as a Bar diagram, the height of the bar would demonstrate the quantity of a category.

2. What is the output of the following line of code?


Pie([1,2],[0,1,1])

a) Error

b) Sliced pie chart

c) Pie-chart

d) Labelled Pie chart

Answer: a

Explanation: Following the syntax of the pre-defined function pie in MATLAB, we find the length of the two arguments passed into pie must be the same. Here, the size of arg1 is 2 while that of arg2 is 3. Hence, MATLAB will generate an error.

3. What is the difference between primary and secondary data in statistics?

a) No difference

b) The former is collected from the field of the investigation while the latter is collected from a separate entity

c) The first set of data received is Primary data while the next set is secondary data

d) The important data is primary data while the lesser important data is secondary data

Answer: b

Explanation: Data collected directly from the field of purposeful investigation is primary data because it is directly used by the one who collects it. If the data, gathered by an agency or a person, is used by a different agency or person for some purpose- there is no direct link between the data and the person requiring it. Thus this is secondary data.

4. The nature of data while using pie plots is ___________ data.

a) Discrete

b) Continuous

c) Polar

d) Time-series

Answer: b

Explanation: Pie plots show the percentage, a category occupies, amongst a dataset containing several categories. Now, if this dataset is not discrete- it is preferable to use pie plot since the height of bar plots might be very close to each other to show significant changes. Hence, pie plots represent continuous data mainly.

5. What would you use to show comparisons of profit of 3 industries over 3 quarters?

a) Histogram plot

b) Bar plot

c) Bode plot

d) Frequency plot

Answer: b

Explanation: The data contains 3 parameters- profit, industry, quarter. We can use the histogram plot if the profits are strikingly different but usually it is not so. So, we should use Bar plot to draw 3 bars for 3 industries showing 3 separate profits over 3 separate quarters.

6. What is the difference between stem plot and histogram plot?

a) No difference

b) Histogram does not have negative values while stem may have negative values

c) Histogram cannot relate 3 variable while stem can

d) Histogram cannot be created in MATLAB

Answer: b

Explanation: Histograms are used to see the frequency distribution of a variable to show the frequency of a class over any interval. So, naturally, a variable cannot repeat with a negative frequency. Stem plot only relates the two arguments it gets in terms of their projected values. So stem can have negative values.

7. To display the partnership of 3 batsman with one batsman, one uses _________

a) Bar-graph

b) Histogram

c) Pie plot

d) Cannot be displayed

Answer: b

Explanation: A bar graph is used to show the contribution of 3 batsmen with one batsman in a partnership. Thus it can be inferred who has contributed highest to the partnership among the three.

8. To display the runs scored by a batsman towards different directions in a field, one uses

a) Bar graph

b) Angle histogram

c) Histogram

d) No graph is suitable

Answer: a

Explanation: The angle histogram graph plots a histogram circularly. So, viewing the field as a circle, one can easily find the area in the field where the batsman has scored the most runs.

9. A cubic system can be represented using the function ____

a) plot3

b) stem

c) display

d) legend

Answer: a

Explanation: The function ‘plot3’ is used to plot a 3d graph. The axes of the system can be mentioned as x,y,z so the plot which will be returned will be for a cube if the length cut off from each axis are equal.

10. To specify different curves in an angle histogram plot, we use the _________ function.

a) legend

b) display

c) gtext

d) mtext

Answer: a

Explanation: The legend function is pre-defined in MATLAB. It is used to print the names of the curves present in a plot. The function is the same for both 2d and 3d plots.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Plotting Multiple Curves”.


1. A student has created a plot of y=t 2 . He is need to show another graph of z=t 3 in the same plot. But every time he hits the plot function- MATLAB generates a plot of z vs t but on a different window. What is the error?

a) It is not possible to plot multiple plots

b) He is not using the line function

c) Maybe he is using stem instead of plot

d) He is not using the hold function

Answer: d

Explanation: The hold command is used to hold the cursor, developed after creating a plot, so that the next graph, when plotted, will appear on the same window where the initial graph was plotted. He may use the line function, but in the code he is using the plot function. So he has to enter the function hold before plotting the graph of z.

2. Does the plot function take multiple arguments to a plot?

a) True

b) False

c) Sometimes

d) Only if the functions are in time domain

Answer: a

Explanation: The plot function can take multiple input arguments to plot multiple graphs. This is an inbuilt function so the nature of the function is, inherently, to take multiple arguments if the arguments are defined.

3. What happens if we don’t stop the implementation of the hold function?

a) Nothing happens

b) MATLAB keeps on generating multiple plots in the same window

c) Error is generated

d) Plot function won’t work

Answer: b

Explanation: Suppose we plot 2 graphs on the same window by using the hold command. If we don’t stop the implementation of the hold function, MATLAB will keep on generating plots on the same window. So the user won’t get a separate plot if he wants.

4. Is histogram a kind of multiple plots?

a) True

b) False

c) Cannot be determined

d) There is no such thing called Histogram

Answer: a

Explanation: We are plotting a particular data set for different entities. The data set may comprise of the same set but each entity is inherently independent from each other. So, we are plotting multiple functions of the same variables. Hence, the histogram is a kind of multiple plots.

5. The function to plot vector fields is ___________

a) quiver

b) pie3

c) ezplot

d) contour

Answer: a

Explanation: The function ‘quiver’ is a pre-defined function in MATLAB. It is often used to plot vector fields in MATLAB. The pie3 function is used to plot a 3-d pie plot. The ezplot generates a 3d plot while the contour is used to generate the contour plot of a specified matrix.

6. How to introduce a title to describe the subplots generated in MATLAB?

a) Use a function

b) Use the title function

c) Use the legend function

d) Use uipanel

Answer: d

Explanation: The uipanel can be used to give a major title to the subplots created. The title name is given as a string input by the following way:

f=figure;

c=uipanel;

c.Title=’Title Name’;

c.TitlePosition=’centertop’

7. Can we have multiple 3d plots in MATLAB?

a) Yes

b) No

c) Maybe

d) Cannot be determined

Answer: a

Explanation: The plot3 function is a pre-defined function in MATLAB. So, it will allow the use to generate multiple 3d plots. This is inherent to the system.

8. The student receives an error while trying to plot multiple graphs using the hold command. What is there error if there is no a syntactical error?

a) Cannot be determined

b) The plot function is not defined with a constant variable range

c) There is no hold command

d) There has to be a syntactical error only

Answer: b

Explanation: If the student is using the hold command, the student has to keep the scale and range of one axis same. Then he can plot the functions of other dependent variables, which depend on the independent variable range previously defined. If the plot function contains an entirely different set of arguments, MATLAB will produce an error.

9. What is the difference between hold on and hold all?

a) no difference

b) hold all holds every plot while hold on holds a specific plot in the chain of argument

c) hold all does not exist

d) hold on is syntactically incorrect

Answer: a

Explanation: Both hold on and hold all commands are used to hold the graph of a function. There is no difference between them. To avoid confusion, one can only write hold to hold a graph and again enter the command hold to release the graph.

10. What is the purpose of the line command if the plot command can be used to directly accept the arguments and generate a plot?

a) Saves complexity

b) We can refrain from using the hold function

c) There is no separate, definite purpose

d) Cannot conclude

Answer: d

Explanation: The use of the line command is primarily seen in plotting the graphs without the hold command. But we can put the arguments within the plot command itself so that we don’t have to put an extra line of code. This saves complexity, although we have increased the length of our code.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “The MATLAB Interface”.


1. Which functions help you to save and load variables?

a)


>> save Lays [a,b]

>> load('myfile.mat')

b)


>> save Lays {a b}

>> load myfile.mat

c)


>> save Lays “a,b”

>> load(myfile.mat)

d)


>> save Lays a b

>> load('myfile.mat')

Answer: d

Explanation: There is a pre-defined function in MATLAB to store the variable values from your workspace permanently called ‘save filename’. Option d is the correct command syntax for calling it.

Output: 

>>a=5;b=a;

>> save Lays a b;     % Now go to workspace and delete the variables

>> load('Lays.mat');%Check workspace.


2. To add comments in MATLAB, use _________

a) //

b) %/

c) /%

d) %

Answer: d

Explanation: The only format for adding and storing comments in MATLAB is to use the % symbol. One can choose to end a comment using %, but it is not needed.

3. To display comments of M-file, we use ____________

a) echo on

b) comment on

c) show %

d) Cannot be displayed

Answer: a

Explanation: The echo command is used to display commands present in an M-file. If the M-file has any comments, the echo command will also display the comments.

4. Where do we need to store a function to call it in other programs?

a) The bin folder

b) Anywhere

c) The MATLAB folder

d) Desktop

Answer: a

Explanation: M-files containing only a function has to be written separately and has to be stored as .m files in the bin folder. If it stored in any other folder, MATLAB won’t be able to access the function file.

5. What are the difference between the ‘help’ and the ‘look for’ command?

a) No difference

b) Syntactical difference

c) Help returns the entire set while look for returns specific commands

d) Help returns all the toolbox while look for returns a single toolbox

Answer: c

Explanation: The ‘help’ command is used to return all the commands surrounding a particular toolbox name entered along with it. The ‘look for’ command is used to return a particular function or set of functions whose name matches with the keyword entered in along with the ‘look for’ command.

6. What will the following set of commands do when they are present in a script file?


stem[y1,y2];

title(‘p’);

print -deps p

a) Plot the discrete graph of y1 and y2

b) There is no stem command in MATLAB

c) Store the graph as a separate file

d) Cannot be determined

Answer: c

Explanation: The given format of the print statement is used to store the graphs of y1 and y2 generated due to previous definitions of y1 and y2. If we only use the print command, the graph y1 and y2 will get displayed.

7. The function to close the windows containing graphs generated from MATLAB is __________

a) close all

b) close graphs

c) delete graphs

d) end all

Answer: a

Explanation: The command close all is a pre-defined function in MATLAB. When it is called, MATLAB will automatically shut down the separate windows that have been opened to view graphs separately. The rest of the options are wrong.

8. What is not displayed by the Workspace?

a) Time of variable generation

b) Standard deviation of the variable values

c) Class of the variables

d) Nature of the variables

Answer: a

Explanation: By right clicking on the Workspace header, we will get to know the characteristics of the variables which are stored in the Workspace and what it can display. The time of variable generation is not present in the Workspace. It can only be seen if the variables from the workspace are saved separately using the command ‘save filename’.

9. MATLAB allows modelling of different control systems using ___________

a) Simulink

b) Control System Toolbox

c) Not available in MATLAB as of yet

d) ezplot

Answer: a

Explanation: Simulink is a separate package which is present in MATLAB. It helps to model and analyze a control system which makes MATLAB a very powerful tool for simulating dynamic systems.

10. How to stop the execution of a chain of commands?

a) Press Ctrl +c

b) Cannot be stopped

c) Only usage of debugging mode is possible in MATLAB

d) Quit

Answer: a

Explanation: It may so happen that we want to pause the execution of a set of commands at a certain point. We only need to press Ctrl and C together to pause it. On the other hand, quit causes the MATLAB software to shut down. Debugging modes are also available in MATLAB.

11. What are MEX files in MATLAB?

a) No such thing as MEX files

b) Helps to analyse commands in MATLAB

c) Allows the user to combine C source files with Matlab files

d) Same as MAT files

Answer: c

Explanation: MEX files are one of the kinds of file modes available in MATLAB. They are saved with a .mex extension. These files help in the association of C source files into the programs written in MATLAB.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “M-Files”.


1. How would you start a debugger in MATLAB?

a) There is no M-file in MATLAB

b) Type edit in MATLAB and press Enter

c) Type debug in MATLAB and press Enter

d) Type M-file in MATLAB and press Enter

Answer: b

Explanation: M-files are simple text files containing MATLAB programs. These can be used to run complex programs easily. In MATLAB, we can type edit to begin writing in Editor/Debugger mode. Typing debug or M-file won’t do any good.

2. What is the extension of script files?

a) .m

b) .mat

c) .script

d) There is a nothing called script file

Answer: a

Explanation: Script files are a kind of M-file. So to save a script file, it has to saved with a .m extension. On the other hand, .mat extension is for MAT files.

3. What is the basic difference between M-files and MAT-files?

a) There is no difference

b) MAT files are binary data files while m-files are ASCII text files

c) M files are binary data files while MAT-files are ASCII text files

d) There is no such thing as MAT files

Answer: b

Explanation: M-files are ASCII text files which are used to simplify our program editing in MATLAB, they are basic text files. MAT files are Binary files created by MATLAB. When we need to save any data from the workspace, it is saved in MATLAB as a MAT file.

4. What does the echo command do?

a) It echoes

b) It shows the comments present in Script files

c) It shows the commands and comments in MAT-files

d) It shows the commands and the comments in M-files

Answer: d

Explanation: The echo command is a pre-defined function in MATLAB. If it is present in an m-file, the command will help to show the commands and comments present in the m-file when the m-file is called in the command window.

5. What will the following command do?


Load m1

a) Load the script file named ‘m1’

b) Load the function file named ‘m1’

c) Load the m-file named ‘m1’

d) There is no Load command in MATLAB

Answer: c

Explanation: The command ‘load’ is pre-defined in MATLAB. It is used to load an M-file and run it to show get the output which is supposed to be generated from the m-file. Not the m-file can be a script file or a function file. Since the question does not mention whether the m file is a script or a function file, the possible option is Load the function file named ‘m1’.

6. What will the following command do?


Save workspace

a) Saves the entire workspace as MAT file

b) Saves a variable named ‘workspace’ as MAT file

c) Saves the entire workspace as m file

d) Saves a variable named ‘workspace’ as m file

Answer: b

Explanation: The save command is used to save a variable from workspace. So the above command will only save a single variable, named ‘workspace’, from the workspace itself. It won’t save the entire workspace.

7. How do you create a function file in MATLAB?

a) Begin m-file with function definition

b) Begin script file with function definition

c) There is no such thing called function file

d) An m-file is only a function file

Answer: a

Explanation: If an m-file starts with a function definition, it becomes a function file. This file can be called to generate a desired output multiple times. As MATLAB allows the making of such files, complicated big programs can be broken down to simplify the nature of the entire MATLAB program.

8. A student is repeatedly calling a function file but gets no output. She has checked the file repeatedly so finally she asked her teacher about it. The teacher checked everything and finds the error and gives her a scolding. What is a silly mistake?

a) She was calling the wrong function

b) She has placed a semicolon at the end of the line which computes the desired values

c) She has called a .m file

d) She was calling a script file

Answer: b

Explanation: If we write a function file, we should not put a semicolon at the line which computes a value. This will lead to the passing of cursor to the next line after the function is implemented without showing any output. So it was good that the teacher scolded her.

9. A function is not returning values according to desired input values. What should be the correction?

a) Include clear all at the beginning of function file

b) Include close all at the beginning of function file

c) Include echo on in the function file

d) Cannot be solved

Answer: a

Explanation: Even though the variables defined within a function are local variables, they might get affected due to the previous usage. So while execution of the same function, the user might get a different answer. Thus it is advised to include clear all to remove all previous definitions of variables. The command ‘close all’ is used to clear the previously created graphs.

10. MEX files work on JAVA.

a) True

b) False

Answer: b

Explanation: MEX files are files written in C language. They can be integrated with MATLAB. They won’t work on JAVA.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Loops”.


1. What is the default increment value in a for-loop?

a) 0

b) 1

c) An increment value is necessary

d) 0/1

Answer: b

Explanation: When we are going to start a for loop in MATLAB, it is not necessary to assign a specific increment value. The default increment value will then be taken as 1.

2. What is the output of the following code?


for i=1:4

for j=1:4

a=5;a=a+5;

end

end

a) No output will be shown

b) a=10;

c) a=80

d) Error in the code

Answer: b

Explanation: We have put a semi-colon after a=5. So, for both the “for loops” for i and j, we will keep assigning 5 to ‘a’ repeatedly. At last, we will do a=a+5. This will make ‘a’ as 10.

3. What is the output of the following code?


for i=1:5

for j=1:6

a(i,j)=input();

end

end

a) No output

b) Error

c) Asks user to input a 5*6 matrix

d) Asks and displays a 5*6 matrix

Answer: b

Explanation: The syntax for input is wrong. There should be a pair of single inverted commas within the syntax, even though we don’t have to write anything necessarily within them. But to take any input, we have to use the

syntax: a(i,j)=input(‘’) OR a(i,j)=input(‘Enter value coloumn-wise:’)

We can choose to place a semi-colon at the end, then the matrix won’t be displayed after every input.


4. What is the size of i after the following code is run in MATLAB?


for i=5:1

i=i-2;

end

a) No output

b) 0*0

c) i=-1

d) Error

Answer: b

Explanation: The above loop does not run because the default increment value in MATLAB is +1. We have to assign a decrement value separately if we want the index value to decrease for a for-loop. If we set a decrement value of -1, the loop will run for 5 times and the final value of i will be -1. No output will be shown due to a semi-colon but the question is what will be the size of i.

5. A break statement will leave the outer loop.

a) True

b) False

Answer: b

Explanation: In case of nested for-loops or while-loops, the break statement will remove control only form the loop where it was invoked as a command. It won’t come out from the outer loop.

6. How many times will the following loop run?


for i=1:5

if(i<3) break

a) No output due to some error

b) 1 times

c) 0 times

d) 3 times

Answer: c

Explanation: The for-loop is not terminated. Any statement or a group of statement, in a for-loop, will be executed effectively only after the end statement is used to terminate the loop.

7. What is the nature of the following code?


j=0;i=1;

while(j>5)

for i=1:8

j=j+i;

end

end

a) j=0 & i=1

b) j=1 & i=0

c) i=8 & j=36

d) Error

Answer: a

Explanation: We find that the inner while loop goes into an infinite loop. MATLAB is unable to compute the value so it returns j=0 as was initialized. The same goes for i=1. If there was no while loop, option i=8 & j=36 would have been the output. There is no error in logic.

Output: No output will be shown since we have placed a semi-colon after j=j+i. But the workspace will store i & j as 1 & 0 respectively.

8. A for-loop can have multiple index values.

a) True

b) False

Answer: a

Explanation: A for-loop has a single index. But it has multiple index-values during successive iterations.

9. There can be multiple decision variables for while loop.

a) True

b) False

Answer: a

Explanation: We can provide multiple conditions to end a while loop. The conditions can be different so we can have multiple decision variables for while loop.

10. What will be the output for the following code?


k=0;i=0;

 while(k<1 && i<1)

k=k+1;

i=i+1;i=i-k;

end

a) i=0,k=1

b) i=0,k=0

c) i=1,k=0

d) i=1,k=1

Answer: a

Explanation: We find that i become 0 at the end of the first iteration while k becomes 1. Since k<1 is a condition for the while loop to terminate, the while loop gets terminated. In case of multiple condition, the while loop will be terminated even if one condition is satisfied.

11. How do we break from an infinite loop without keeping a break statement within the loop?

a) Press Ctrl+C

b) Press Ctrl+Z

c) Loop won’t be terminated

d) Press Ctrl+X

Answer: a

Explanation: If we begin an infinite loop, by choice or as a silly mistake, we can terminate the loop manually if we forget to introduce a break statement as necessary. We can choose to press Ctrl + C and the loop will get terminated at the same instant.

12. What will the following code do?


j=0;i=5;

while(j<0)

j=j-1; i=i+5;j=i;

end

a) Nothing

b) j=0 & i=5

c) Error

d) Cannot be determined

Answer: b

Explanation: We observe that the while loop will enter into an infinite loop. Hence the final value of i and j won’t be determined by MATLAB. MATLAB will retain the values for i and j as they were initialized. Hence j will remain 0 and i will remain 5. There is no error in the code.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Presenting Results”.


1. How would you plot multiple graphs in MATLAB?

a) Using the hold function

b) Using the mplot function

c) Using the mstem function

d) It cannot be done in MATLAB

Answer: a

Explanation: The hold command is a pre-defined function in MATLAB. It allows the control to remain in the window where which was generated by MATLAB, the first time we type a command to plot any kind of graph. Then on we can plot multiple graphs on the same window.

2. How do you show the program of an MAT file?

a) The program should contain the echo command

b) The program should contain the showprog command

c) The program should contain the diary command

d) The program cannot be shown while running a MEX file

Answer: d

Explanation: MEX files are not M-files. They are binary files which store the values of variables present in the workspace. So there is no question of showing the program of a MAT file.

3. The help command works only for a pre-defined function in MATLAB.

a) True

b) False

Answer: a

Explanation: The help command will only show the nature of functions of any command which is already existing in the MATLAB directory. If we want to show the purpose of our written function, we have to add comments in our m-file and then enter the echo command.

4. What is the equivalent of subplot ?

a) subplot

b) plot

c) It is not possible

d) axes

Answer: d

Explanation: While using subplot , we have allocated memory as a 2-D matrix for only 1 graph. This is similar to the axes command which generates an empty graph. This is pre-defined in MATLAB.

5. It is not possible to store graphs as MAT-file.

a) True

b) False

Answer: a

Explanation: MAT files save data from the workspace. A graph, plotted among different variables, cannot be stored in MATLAB since MAT-files are files used to store values from the workspace.

6. The command used to reflect the files from a disk into the workspace is _______

a) load

b) show

c) disp

d) it is not possible

Answer: a

Explanation: The load function is pre-defined in MATLAB. It is used to load variables and/or data from the disk to the workspace.

7. The format for 5 digit representation along with exponent is __________

a) short e

b) short g

c) short exp

d) 4 digit along with exponent value can be represented

Answer: a

Explanation: The short e format is used to represent a result with 5 digits and an exponent term. Now, this is pre-defined in MATLAB. Short g and short exp are not present in MATLAB. We cannot use a representation of 4 digits and an exponent as it is not defined in MATLAB, as of yet.

8. Which operator is used to prevent the printing of insignificant zeros?

a) %o

b) %nz

c) %g

d) It is not possible

Answer: c

Explanation: %g is used to represent any number, which has a fixed number of digits or a number with an exponent, with no insignificant zeros. This is present in the MATLAB directory only.

9. The function to plot a graph with both axes on logarithmic scales is __________

a) loglog

b) log

c) semilog

d) not possible

Answer: a

Explanation: There is no command called semilog or log to plot a graph with logarithmic scales. However, we have the loglog function, pre-defined in MATLAB, which allows us to plot a graph of two variables where both the variables are scaled logarithmically.

10. We cannot plot a discrete and continuous relationship in the same graph.

a) True

b) False

Answer: b

Explanation: We can plot a discrete and continuous relationship in the same graph. We have to use the hold command and change the scaling of the variables a bit if at all needed, so that the discrete and continuous relationship looks prominent enough in the same graph. We have to use the hold command efficiently.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Fine Tuning”.


1. How will one escape from printing graphs of variables, whose value gets changed for the program?

a) Use the clear all command at the beginning

b) Use the close all command at the beginning

c) Use the clc command

d) Cannot be escaped

Answer: a

Explanation: The clear all command keeps all the local variables of the function unaffected i.e. they prevent their values from getting changed due to some previous usage of the function. The close all command closes all the graphs the clc command removes the written code.

2. A loop is used to avoid repetitive writing of the same function in the code.

a) True

b) False

Answer: a

Explanation: The purpose of using loops is to avoid writing the same line multiple times. The same line may be a particular function which computes a certain value. For the sake of accuracy, we may run the function multiple times, within a loop.

3. How will you return to execution from debugging mode?

a) Use the dbcont command

b) Use the return command

c) Use the dbcont & return command

d) Use the keyboard command

Answer: c

Explanation: While debugging, the user can choose to insert a set of instruction to change the nature of the already written program. To return to continue execution, the user can enter either dbcont or the return command.

4. The plotting of 3d plots and 2d plots requires separate windows. But the user has entered the hold on command. What is to be done?

a) Use the pause command

b) Use the hold off command

c) Use the close command

d) Nothing can be done

Answer: a

Explanation: The hold off command is necessary to plot multiple graphs in the same window. Thus multiple 2d graphs or multiple 3d graphs can be drawn on the same window. But the pause command is used to keep the plot of 2d graphs and wait before generating 3d graphs. The close command closes any existing graphs.

5. What will be the output of the following code?


T=-5:1:5; y=sin(T); plot(T,y)

a) No output

b) A perfect sine curve

c) A broken sine curve

d) Cannot be determined

Answer: c

Explanation: The sine curve is a continuous signal or a discrete signal. So the tendency of every point in the curve has to follow a radian frequency and not a step frequency. Here the frequency of time is stepping up by 1, so the sine curve will only consist of 11 values, which will lead to the sine curve appearing to be broken.

Output: matlab-questions-answers-fine-tuning-q5

6. How would you expect to see exponential inter-relation in a logarithmic scale?

a) A straight line

b) A curved line

c) Depends on the exponent

d) Depends on the log scale

Answer: a

Explanation: The exponential inter-relation will appear as a straight line in a log scale. This is because logarithmic scale and exponential nature follow a linear relationship. If there are no other terms than exponentials in the expression, the graph will be a linear one.

7. There will be a problem in computing the logarithm of a negative number.

a) True

b) False

Answer: b

Explanation: While trying to compute a value for the logarithm of a negative number, MATLAB will return an imaginary value. We can do problems which need to compute the logarithm of a negative number.

8. Global variables must be mentioned _____ an M-file.

a) at the top in

b) anywhere in

c) out of the

d) there is nothing called global variables

Answer: a

Explanation: Mentioning the global variables at the top of an M-file allows the user to prevent any error rising to usage of the same variable unconsciously. If we declare it anywhere, it may so happen that we would need it at the beginning. Hence- it is plausible to declare it at the top of an M-file.

9. To stop execution, press _____

a) Ctrl+C

b) Use pause command

c) Use end command

d) Use keyboard command

Answer: a

Explanation: The pause/keyboard command is used to suspend execution for a certain time. If we press Ctrl+C, execution will be completely stopped. The end command is used to end loops of any kind.

10. The function definition is shown when we use the look for the command.

a) True

b) False

Answer: b

Explanation: The look for command shows the H1 line used in a function. The look for command will describe only inbuilt functions and not user-defined function. The H1 line is comment line just after the function definition so the look for command does not return the function definition.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Suppressing Output”.


1. Graphs are not suppressed by the ‘;’.

a) True

b) False

Answer: b

Explanation: The commands to generate any kind of graph will always result in an opening of a new window when they are used as required. The ‘;‘ won’t suppress it.

2. What will be the output of the following code?


close all;

for x = 1.5 : .5 : 2;

y=3; 

x=y+3

 clc

end

a) No value will be stored

b) The result will be printed

c) The result will be printed twice but no value will remain in the Workspace

d) The loop will not run

Answer: c

Explanation: The loop will run twice and the final value of y is 5 while that of x is 2. Each time the loop runs, no result shall be printed since the ‘ ; ‘ at the end of the last line suppresses the result and it gets stored in MATLAB.

Output:  x = 4.5

         x = 5

3. What will be the output of the following code?


for i = 1 :4: 5

y=i+1

clear i

end

a) y=5; i=2

b) y=5, printed twice

c) Loop will run once, y=2

d) Infinite loop

Answer: b

Explanation: The index of a loop is a separate variable. It will get added to y in the first iteration and y will have value 2. Now even though we have the index i=1 in the workspace, it will get cleared from it but the loop will continue with i=1. So the final value of y will be y=5+1=6. The loop won’t be an infinite loop.

Output:  y = 2

         y = 6

4. Clear will removes all graphs.

a) True

b) False

Answer: b

Explanation: Clear all removes variables from the workspace. It does not remove graphs.

5. What will be the output of the following code?


for i=1 : 3

i=i-1

end

a) i will be printed thrice as 0,1,2 successively

b) Infinite loop

c) No output

d) i=2

Answer: a

Explanation: The index of a loop is a separate variable. The value of I at the first iteration is 1 so at the end of the first iteration, it will print 0. This does not mean that the index variable will also be 0. Thus So i will be printed thrice as 0,1,2 successively.

Output: i = 0

        i = 1

        i = 2

6. How can we close all graphs in MATLAB?

a) Using the close command

b) Using the clear all command

c) Using the close all command

d) Using the clear command

Answer: b

Explanation: The in-built command to close the windows containing graphs is ‘close all’. This command should be placed at the beginning of a function which creates graphs so that future commands do not affect the graph generated every time the function is called.

7. clc in a function will clear the function.

a) True

b) False

Answer: b

Explanation: Suppose we have the clc command at the end of an M-file. The purpose of clc command is to clear the command window. So when we call the function, it will clear the command window but the function will not be cleared.

8. What will be the output of the following code?


for i = 1 : 1

p=i-1

i=i+1;

clc

end

a) i=2

b) p will be printed

c) Error

d) Cannot be determined

Answer: a

Explanation: The value of i won’t be printed since we have ended it with a semi-colon. The value of p will get printed and then the clc command will remove it from the command window. Instead, the value of I will be stored in the workspace as 2.

9. ___________ will give a hint that the file is closed.

a) Fopen

b) Fclose

c) Gclose

d) clc

Answer: b

Explanation: The Fclose command will close the file and returns an integer value to the monitor screen to signify the operation of the command. If it returns 1, the file is closed.

10. To delete one variable but not the entire workspace, we need to mention the variable name after the clear command.

a) True

b) False

Answer: a

Explanation: The clear command removes every variable from the workspace. If we only mention the variable name, it will delete only that variable from the workspace and not the entire workspace will be cleared.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Data Classes”.


1. What is the nature of storage of anything in MATLAB?

a) Stored as arrays

b) Stored as a data structure

c) Stored as a variable

d) Depends on nature of the input

Answer: a

Explanation: An array is a data structure. But, even a single variable in MATLAB is stored as a 1*1 array. Every variable we use in MATLAB is stored as an array.

2. What is the nature of the following variable, in MATLAB?


A=[1 , ‘Poland’, ‘Nail polish’,’Hit’,’Ler’]

a) String

b) String-integer

c) Integer-string

d) Cannot be determined

Answer: a

Explanation: MATLAB will take the variable A as a string variable. It will replace the 1 with an unknown value.

3. What is the starting index of an array in MATLAB?

a) 1

b) 0

c) Depends on the class of array

d) Unknown

Answer: a

Explanation: Unlike C, the starting address of an array in MATLAB is 1. Hence if we declare an array named arr and type arr, we will get an error. The first entry to the array will have the index 1.

4. All data types are converted to ____ before mathematical operations.

a) Single

b) Double precision

c) Floating

d) Unsigned

Answer: b

Explanation: All mathematical operations are done with double precision in MATLAB. Hence, all data types, single and floating, are converted to double data types.

5. What is the return type of angles in MATLAB?

a) Degrees

b) Radians

c) Radians & Degrees

d) Depends on the user

Answer: b

Explanation: This is characteristic of MATLAB to take input for angles and return angles in radians. Thus entering sin in MATLAB will not return 1, but entering sin will return 1.

6. To represent only two digits after the decimal point, the format we use is ______

a) Long e

b) Short

c) Hex

d) Bank

Answer: d

Explanation: The Long e format is used to represent a total of 15 digits while short is used to represent 4 digits after decimal. The formal Hex is used for the hexadecimal representation of bits. The bank format is also called ‘Dollars and Cents’. It is used to display only two digits after the decimal.

7. How do we change the nature of the display of the numerical answer?

a) Use the format command

b) Use the class command

c) MATLAB provides intuitive display

d) Not possible

Answer: a

Explanation: The format command is used to change the display of numerical answer. If the format command is not invoked, MATLAB will always show four digits after decimal point and all the digits before the decimal point.

8. Strings are stored in ____ variables.

a) Character

b) String

c) Stack

d) Array

Answer: a

Explanation: All the variables are stored in the form of arrays. So strings are also stored as character variables. The variables are not called string variables.

9. What will be the output of the following code?


ilaplace(1/syms p^2)

a) t

b) s

c) error

d) ilaplace is not present in MATLAB

Answer: c

Explanation: We need to declare p as a symbolic variable before passing it to the ilaplace command. But here, MATLAB won’t show that p is not defined. It will show ‘Unexpected MATLAB expression’ since the command ilaplace is defined to accept variables already defined. It won’t allow defining a variable in the function parameter itself.

10. What is the output of the following code?


format bank

sym(sqrt(3))

a) 1.72

b) 1.73

c) 3 

d) sqrt

Answer: c

Explanation: sym is used to represent the input arguments of the command in a symbolic form. Hence, MATLAB won’t evaluate the value of the square of 3. It will represent it symbolically as 3  .

Output >> format bank

>> sqrt (3)

Ans = 1.73.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Functions and Expressions”.


1. How many expressions are there in the following mathematical relation?


 a=sqrt(log(sqrt(x+y)))

a) 2

b) 3

c) 1

d) 4

Answer: b

Explanation: The given relation has 3 functions but it has 4 expressions in itself. sqrt is an expression while sqrt is the function. log) is a separate expression while log is the function. sqrt)) is entirely an expression. The entire mathematical relation is an expression used to describe that a is equal to sqrt)); this is important since we are sure about the nature of the relationship between a,x and y. Hence, there are 4 expressions which successfully describe the mathematical relation between the variables a,x and y.

2. How many functions are there in the following mathematical relation?


p=sin(pi*(log(x))

a) 2

b) 3

c) 1

d) 0

Answer: a

Explanation: There are only 2 functions used to describe a meaningful relationship between p and x. They are the sin and log. Now, the expression ‘pi*log’ is not to be confused as a function since we have not created a function i.e. we have not made a self-containing block of statements with an algorithm to compute the value after multiplying pi with log. The ‘*’ operator is used directly to the expression does not serve as a function, it shows an operation. Hence there are only 2 functions.

3. What are the minimum numbers of expressions which will be required to express a mathematical relation?

a) At least 1

b) At least 2

c) At most 1

d) Depends on the number of variables

Answer: d

Explanation: If we have a very big expression relating a variable y with any no. of variables x 1 ,x 2 …x n we can put the entire expression on the right hand side within a function and reduce the expression to

y=func(x 1 ,x 2 ,x 3 …x n )

This contains two expressions only. The function, ‘func’, may contain a set of 10000 statements. But we have simplified the expression to demonstrate a mathematical relation between y and all the other variables of the right-hand side, provided we are sure about the nature of the function ‘func’.

4. Is it possible to reduce the number of expressions in the following mathematical relation?


a=sin(pi*log(x))

a) Yes

b) No

c) Maybe

d) Impossible

Answer: a

Explanation: We can define a function, say func, which contains the block of statements, required, to compute the given relation and return the value. Then we can say

a=func

We have 2 expressions now while the previous statement had 4 expressions. Hence, we have reduced the number of expressions.

5. Is it possible to reduce the number of functions in the following mathematical relation?


l=cos(2*pi*sin(n/x))

a) Yes

b) No

c) Maybe

d) Obviously

Answer: b

Explanation: We cannot reduce the number of functions which are required to express a mathematical relation amongst variables. This is because those functions compute the value of the dependent variable for any value of the independent variable. In some cases, we may approximate the values of the dependent variable- but we are approximating the functional operation, we are not deleting the function.

6. The teacher has given the assignment to find the sum of 2 numbers. But the code should not contain the ‘+’ operator. What is to be done?

a) Use a function

b) Add the values and print the sum directly

c) Use an expression

d) Cannot be done

Answer: a

Explanation: The power of a function is to hide the statements which are used to complete our task. So the student can create a function file to add two numbers. Hence, the code will not show the ‘+’ operator but it will be used implicitly.

7. How many expressions are used to describe a mathematical relation between a, b and c?


b=9; c=4;

a=b+c;

a) 4

b) 2

c) 3

d) 1

Answer: b

Explanation: The code has 4 expressions, ‘b=9’, ‘c=4’, ‘b+c’, and ‘a=b+c’. The mathematical relation is described by ‘a=b+c’ only which contains 2 expressions. Hence, there are two expressions that has been used to describe a mathematical relation between a, b and c.

8. A mathematical statement is a combination of functions and variables only.

a) True

b) False

Answer: b

Explanation: An expression is a combination of variables, operators and functions. It is not necessary that only functions and variables are present in a mathematical expression. The statement ‘a=b+c’ contains no functions, but it only performs the addition operation between b and c and assigns the value to a. The statement a=sum shows no mathematical operation explicitly since the operation is done by the function itself.

9. What is the command which can be used to see the expressions within a user-defined function in MATLAB?

a) help

b) look for

c) echo on

d) cannot be seen

Answer: c

Explanation: A user-defined function is a function file. The commands ‘help’ and ‘look for’ will only return the nature of in-built function. If the function file has ‘echo on’, it will display the expressions in the function file while executing. This is because function files, though they are different from script files, are inherently M-files.

10. What are mathematical expressions?

a) Any mathematical relation

b) Any mathematical operation

c) Any mathematical conversation

d) Any mathematical function

Answer: b

Explanation: A mathematical function is used to relate a dependent variable with an independent variable so it is used to operate on the independent variable. Similarly, any mathematical relation is used to relate an independent variable with a dependent variable. This is also an operation since based on the value of the independent variable, we comment on the value of the dependent variable. Hence a mathematical expression is simply any mathematical operation.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Complex Arithmetic”.


1. Which command is used to find the argument of a complex number?

a) atan2

b) args

c) abs

d) cannot be determined

Answer: a

Explanation: The argument of a complex number is only the angle which satisfies the cartesian equations used to represent the real and imaginary part of the complex number. Thus atan2 is the in-built function to find the angle or the argument, in MATLAB. abs is used to find the modulus of the complex number. args is not a valid function in MATLAB.

2. What is the class of the complex number?

a) double

b) symbolic

c) character

d) array

Answer: b

Explanation: Since the complex number represented in MATLAB uses ‘i’ as a symbolic character, the class of any complex number is symbolic. It is not double and it is certainly not a character. An array is the general class of any variable or expression used in MATLAB.

3. What is the argument of -1-i in MATLAB?

a) -3*pi/4

b) pi/4

c) 5*pi/4

d) -7*pi/4

Answer: a

Explanation: We observe that the complex number lies in the 3 rd quadrant. Hence, we conclude that the argument of the complex number -1-i will be -3*pi/4 in MATLAB. -7*pi/4 is equivalent to -3*pi/4. Pi/4 is 5*pi/4 again.

4. What will be the output of the following code?


atan2(-1,1)

a) Error

b) -pi/4

c) -.7854

d) 0

Answer: c

Explanation: MATLAB returns all values of angles in radians. Hence, we will not see the output as -pi/4. The argument is -pi/4 but MATLAB will return -.7854.

5. The modulus of z, z conjugate and -z are not equal in MATLAB.

a) True

b) False

Answer: b

Explanation: The modulus of z, z conjugate and -z are equal. The magnitude of the modulus is always a positive number. It is independent of the positive or negative nature of the real and imaginary parts of the complex number.

6. What will be the output of the following code?


z=2+3i/(i99)

a) z conjugate

b) -z

c) -3+

d) -1

Answer: d

Explanation: Following the precedence of operators,

2+3i/(i 99 )=2-3=-1. If we had given 2+3i within brackets, the value would have been -3+. The answer won’t be -z or z conjugate.

7. What is the output of the following code?


t=-i:.01*i:i; p=exp(2*t);plot(t,p)

a) a sinusoidal signal

b) an exponential signal

c) a discrete sinusoidal

d) no plot

Answer: d

Explanation: No plot will be generated. This is because colon operands cannot have complex arguments. It has to be real arguments.

8. What is the command used to check the real part of a complex number in MATLAB?

a) abs

b) realc

c) real

d) cannot be checked

Answer: c

Explanation: The command to check the real part of any complex number is real. It is an inbuilt function in MATLAB.

9. Which of the following command can be is used for complex arithmetic?

a) abs

b) atan

c) realc

d) imagc

Answer: a

Explanation: The abs command is used to get the modulus of any complex number. The rest of the options are wrong because they should be ‘atan2’, ‘real’ and ‘imag’.

10. What will be the output of the following code?


abs(i)

a) 1

b) -1

c) Error

d) i

Answer: a

Explanation: The abs command is used to find the magnitude of the complex argument given to it. Since magnitude is a positive value, the output will be a positive value and not -1.

Output: 1

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Linear Systems”.


1. What is a linear system?

a) A system which follows homogeneity and additivity

b) A system which follows additivity

c) A system which follows homogeneity

d) Almost every system is linear

Answer: a

Explanation: A system which follows homogeneity and additivity is called linear system. This comes from the definition of superposition and here is the proof:

Taking a system with which produces y 1  as output for an input x 1  and an output y 2  for an input x 2 ,

HOMOGENITY: For input ax 1 , output should be ay 1  and for input bx 2 , output should be by 2 .

ADDITIVITY: For a input of sum of x 1  and x 2 , output should be the sum of a y 1  and y 2 , i.e. the sum of individual response

Finally, if for an input of the sum of ax 1  and bx 2 , if we get the output as sum of ay 1  and by 2  the system is both homogeneous and additive. This is similar to the superposition principle. No the system is linear.

2. What is the output if the following code?


if(eig(A)==eig(A’))

disp(‘True’)

a) True

b) No output

c) False

d) Error

Answer: d

Explanation: The syntax of the if control structure is wrong. While writing the logical expression, we cannot put it under brackets. If the brackets were removed, True would have been displayed.

3. A student has to find a solution for a system of equations having three variables. He has defined the coefficient matrix as C while the variable matrix as d. He observes that the system is homogeneous. So, to find the solution, he must first check

a) Consistency

b) Homogeneity

c) Heterogeneity

d) Linearity

Answer: a

Explanation: If the system of equations is not consistent, the student cannot ever get a solution for the system of equation. He has to check consistency by finding the rank of the matrix. Thereafter he can comment on the nature of solutions the system possesses.

4. The command to find the eigen vector of a matrix in matrix form is _____________

a) eig

b) eig

c) eigen

d) eig

Answer: b

Explanation: The in-built function to find the eigen values of any matrix in MATLAB is eig. But, to display the result in matrix form- we use eig. This nature of the eig command is in-built in MATLAB.

5. The nature of the eigen matrix displayed in MATLAB is ___________

a) Unsorted

b) Sorted

c) Sorted in Ascending order

d) Sorted in Descending order

Answer: a

Explanation: The eig command will return the eigen values of the matrix ‘a’ in a matrix form. But, it will give it in an unsorted manner- the elements will be placed on the principal diagonal. To sort them, we need to use the sort command- this will sort the columns in ascending order.

6. Checking the linearity of a system, the first thing we need to check is whether the system is __________

a) Homogeneous or not

b) Consistent or not

c) Superposition

d) Depends on the representation of the system

Answer: d

Explanation: First we need to check if the system is represented by a set of equations or it is represented in terms of signals. If it is represented by a set of equation, we need to go for homogeneity first. If it is represented by the observation of input-output signals, we need to go by Superposition.

7. In MATLAB, how can we check linearity of systems represented by transfer function?

a) Check waveforms after superpostion

b) Compare rank of matrices

c) Go for Rouche’s Theorem

d) Intuition

Answer: a

Explanation: Since we have the transfer function of a system, we need to apply superposition and compare the waveforms generated after applying the method of superposition. Rouche’s Theorem is for a system of equations represented by matrices and it is the method of comparing ranks.

8. How can we check in MATLAB if an electrical circuit is linear or not?

a) Check consistency

b) Superposition

c) Superposition via Simulink

d) Check homogeneity

Answer: c

Explanation: We can model our circuit in Simulink and then apply the superposition theorem to check if at all the circuit is following superposition theorem. To apply the theorem, find the I/V relationship across any branch due to a single source and switch of the rest of the sources. Repeat this process for all the individual sources. Finally, turn on all the sources and check whether the I/V relationship is equal to the superposition of all the I/V sources previously calculated.

9. How can we find the solution of a nonhomogeneous system of equations without dealing with the rank of matrices?

a) Rouche’s theorem

b) Cramer’s rule

c) Gauss’s law

d) Cannot be done

Answer: b

Explanation: It is easier to find the solution of a system of equations for a non-homogeneous system using Cramer’s rule. Now, the process is time consuming since we need to find higher order determinants for higher order systems. This is why we go for Rouche’s theorem by hand. But MATLAB computes determinants very fast. Hence, without finding the rank, we can find the solution of a system of nonhomogeneous equations.

10. For a homogeneous system, Cramer’s rule will always yield a trivial solution in MATLAB.

a) True

b) False

Answer: a

Explanation: The process of Cramer’s rule will always yield a solution for the variables in a system. But for a homogeneous system with no constant value, it will yield a 0 as a solution. Hence all the variables will get a 0 as a solution, there-by yielding a trivial solution. This doesn’t imply that the system is inconsistent- this is why we go for comparing ranks, it will allow us to establish a more pertinent justification of the nature of the system.

11. To apply Cramer’s rule, the condition is _________

a) Non-homogeneous system of equations

b) Homogeneous system of equations

c) Determinant of co-efficient matrix is not equal to 0

d) No condition

Answer: c

Explanation: If the determinant of co-efficient matrix is 0, all the solutions will come to be Infinite. Thus, this is the condition to check before going for Cramer’s rule to check the solution of any system of equations.

12. To apply superposition in MATLAB, the condition, one of the condition is ___________

a) No active element is present except sources

b) No passive element is present

c) System should have unilateral elements

d) Nothing needs to be checked

Answer: a

Explanation: Superposition will definitely fail in presence of active elements. A system containing only passive elements will always follow superposition. Superposition theorem fails for unilateral elements., the network must have only passive elements.

13. A second order system with no initial condition is always linear.

a) True

b) False

Answer: a

Explanation: The superposition theorem will yield the nature of linearity of a system. For a system defined by an n-th order differential equation, if there are no initial conditions- the system will always be linear.

14. To check the rank of a non-singular square matrix, we have to use ___________

a) not required

b) rankm

c) rankmatr

d) rank

Answer: d

Explanation: Since the matrix is non-singular, the rank is the highest number of rows or columns  to get a value of the rank.

15. A student aims to use Cramer’s rule to find a solution for a homogeneous system. But while finding the solution, he observes that he is getting infinity as a solution. The code is


p=X.\C

X is the matrix created by replacing a column with constant co-efficients in the equation.

C is the co-efficient matrix

P is one of the variables in the system

Is this a proper justification?

a) Yes

b) No

c) Maybe

d) It is not possible to find solutions in MATLAB

Answer: b

Explanation: The code should have been p=X./C. Since the system is homogeneous, X is always 0. So, applying Cramer’s rule will always yield a trivial solution. But here the student gets or ‘Inf’ as an answer since according to his code, C will be divided by 0- this isn’t really the case. Hence, this is not a proper justification.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Differentiation – 1”.


1. Which rule does MATLAB use while differentiating a set of functions?

a) u-v rule

b) by parts

c) no pre-defined rule

d) not possible

Answer: a

Explanation: If we give an argument within our command diff which is a product of multiple functions or division of two functions; we will get the result that will be generated according to the u-v rule. This makes MATLAB very versatile for the applications concerning differentiation.

2. There is no difference between a difference equation and a differential equation.

a) True

b) False

Answer: b

Explanation: There are many differences between a difference equation and a differential equation. But the most important would be that a difference equation takes finite steps of changes of our changing variable while a differential equation takes an infinitesimal change in our changing variable.

3. For the existence of the n th  derivative of an equation, the equation should have __________

a) Initial values

b) At least one independent variable

c) At least one dependent variable

d) No such condition

Answer: b

Explanation: Derivatives are calculated with respect to a change in an independent variable. Hence for deriving a derivative- the equation should have at least one independent variable so that we can find the derivative with respect to a change in that independent variable.

4. What will be the output of the following code?


syms x;diff(sin(x)\x2)

a) /sin – (x 2 *cos)/sin 2

b) cos/x 2 – )/x 3

c) x 2 *cos + 2*x*sin

d) Error

Answer: a

Explanation: We observe that sin\x 2 has a back slash. This, in MATLAB, implies that x 2 is divided by sin. Hence the answer is /sin – (x 2 *cos)/sin 2 . If it would have been a front slash, the answer would have been cos/x 2 – )/x 3 . If there was a ‘*’ sign, the answer would have been ‘x 2 *cos + 2*x*sin’.

5. What is the data type of y?


y=diff(x2*cos(x) + 2*x*sin(x))

a) Symbolic

b) Double

c) Array

d) Symbolic Array

Answer: d

Explanation: Every element saved in the workspace is stored as an array. The class of the array will be symbolic for y since we haven’t specified a value for x. If we give a value of x, y will be stored as Double.

6. The output for diff(p 2 ,q) is _______

a) 0

b) 2*p

c) 2 dp/dq

d) Error

Answer: a

Explanation: We are differentiating the function ‘p 2 ’ with respect to q. Hence the value will be 0. The 2 nd argument in the diff command is the variable, with respect to which- we differentiate our function.

Output: 2*p

7. What does the following code do?


syms m,y,x,c;

y=mx+c;

diff(y)

a) Calculate m

b) Calculate slope

c) Error

d) Calculate divergence

Answer: c

Explanation: While using syms, we can’t instantiate multiple symbolic variables using a comma. We will have to enter them with space in between. Hence MATLAB returns an error. If we remove the comma, the code will calculate the slope of ‘y=mx+c’.

8. What is the nature of ode45 solver?

a) 2 nd ordered R-K solver

b) 4 th ordered R-K solver

c) 1 st order R-K solver

d) Adams solver

Answer: b

Explanation: The ode45 solver is an Ordinary Differential Equation solver in MATLAB which is used to solve a differential equation using the Runga-Kutta or R-K method upto 4 th order. This is an inbuilt ODE solver in MATLAB.

9. Ordinary differential equations having initial values ____________

a) Can be solved

b) Cannot be solved

c) Can be modelled

d) Has a trivial solution

Answer: c

Explanation: We have 8 different Ordinary differential equations solvers in MATLAB. They take the initial values, if at all present, into account while solving the Differential equation of interest. Hence, systems which follow a differential equation can be modelled and observed using MATLAB.

10. The current characteristics of RC networks are better analyzed by Laplace than differentiation methods.

a) True

b) False

Answer: b

Explanation: We use the Laplace method to ease the process of solving a differential equation. But, with the help of MATLAB- we can solve them very fast. So, it is obvious to use the ODE solver to calculate the current through the capacitor in RC networks and get a time response.

This set of MATLAB Questions and Answers for Experienced people focuses on “Differentiation – 2”.


1. While solving a differential equation, MATLAB will show us the ___________

a) General Solution

b) Particular Solution

c) Complementary function

d) Depends on the equation

Answer: b

Explanation: When we use dsolve to find the solution of an ordinary differential equation, we get the general solution of the equation. Now, this equation comprises of both the complementary function and the particular integral for the general solution. Hence, it is not that we only get the particular integral as a solution after using dsolve.

2. An example of a function whose derivative  with respect to x is never 0, in MATLAB, is _______

a) sin

b) x n

c) e x

d) does not exist

Answer: d

Explanation: It is not possible that the derivative of a function can never be 0. This is because there will always be a case where the derivative of the function becomes 0 for a certain value of x. This value of x can be real or imaginary.

3. The method of differentiation in MATLAB is pertinent for getting __________

a) Higher order differential equations

b) Lower order differential equations

c) Any order differential equation

d) A certain ordered differential equation, within a range

Answer: d

Explanation: MATLAB cannot find unnecessarily high ordered differential equation. It will compute a differential equation but the order of the differential equation is limited.

4. The output of the following code will be _____________


syms t; dsolve(D(y,t)==2*t)

a) Error

b) t 2

c) t

d) t 2 +C

Answer: a

Explanation: The argument with dsolve has D will make no sense to the diff command. Hence there will be an error, due the undefined variable D. If it was diff, the answer would have been t 2 +C.

5. What is the co-efficient of the output of the code?


diff(x90,39)

a) 0

b) 90!/39!

c) 90!/50!

d) Error

Answer: c

Explanation: x 90 gets differentiate 39 times. So the co-efficient will be 90*89*88*….*51. Hence this is represented as 90!/50!. The answer would have been 0 if the code was diff(x 90 ,91).

6. What is the error in the following code?


diff(‘x87+86’,23)

a) No error

b) Arguments as strings

c) 23 is not given within a pair of inverted commas

d) There is no command as diff

Answer: b

Explanation: The command diff will not yield a function after taking the function with a pair of inverted commands. It will give an empty array as an output. No argument in diff should be given within strings.

7. The ode 23 solver is for higher accuracy.

a) True

b) False

Answer: b

Explanation: The ode23 solver is inbuilt in MATLAB. It is a two to three order Runga-Kutta method solver and it is used for problems requiring lower accuracy.

8. The ode45 takes the function as ___________

a) Simple input argument

b) String argument

c) Input argument

d) Function argument

Answer: b

Explanation: The syntax of the ode45 solver is inbuilt in MATLAB. It takes the function as a string argument. The diff command takes the function as a simple input argument.

9. What is the output of the following code?


syms y; dsolve('y*diff(y)+5=x*exp(3)','y')

a) Error

b) C +  – 10))/2

c) Cannot be determined

d) 0

Answer: a

Explanation: Our second argument in the dsolve command is wrong. If we provide a second argument, it should specify the independent variable. But here we are differentiating y and specifying y as the independent variable. If we write dsolve+5=x*exp’,’x’), the output would be C +  – 10))/2.

10. There are 7 ODE solvers in MATLAB.

a) True

b) False

Answer: b

Explanation: There are total 8 ODE solvers in MATLAB. They are inbuilt in MATLAB and each can be used for solving ODEs with initial values. They also provide varying accuracy.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Integration – 1”.


1. The int function gives the __________

a) general solution of the ODE

b) general solution of the function

c) particular integral of a function

d) complementary function

Answer: c

Explanation: ODE solvers gives a general solution of an ODE. But the int function will give the particular integral of a function without any constant term.

2. What will be the command to find the current through a 1H inductor  whose voltage changes by v=t 2 ?

a) int(‘t 2 ’)

b) intg(‘t 2 ’)

c) int(t 2 )

d) Cannot be determined

Answer: c

Explanation: We can only integrate our voltage equation to get the current as a function of time. The syntax for int(t 2 ) is the correct syntax for the int command. The rest is wrong since the int command does not take string arguments.

3. The command quad cannot do ______ integrals.

a) Definite

b) Indefinite

c) Particular

d) Any

Answer: b

Explanation: If we introduce infinity as an argument to our command ‘quad’, it will result in an error. This is because it will not take Inf as an input limit. It can do definite integral over a finite range.

4. The code quadPrime causes double exponent: use braces to clarify is same as ___________

a) quadPrime causes double exponent: use braces to clarify

b) quadPrime causes double exponent: use braces to clarify

c) quad

d) quadPrime causes double exponent: use braces to clarify

Answer: a

Explanation: Since the first limit provided to our quad command is a lower limit, we will get the answer same for the code quadPrime causes double exponent: use braces to clarify. We need to give the input function with the ‘ . ‘ operator since we are computing the value for every instant and it is adding up.

5. The capacitor voltage due to a current of i=t 4 with v(0 + )=3 is found from using _________

a) ODE solver

b) int command

c) quad command

d) diff command

Answer: a

Explanation: The case for the capacitor has an initial condition. So the int command won’t merely give the voltage, as a function of time, for the capacitor. We need to use the ode45 solver or the ode23 solver. The quad command won’t also give the true solution for a voltage since it doesn’t return the complementary function.

6. The accuracy of quad is ___________

a) very low

b) low

c) moderate

d) high

Answer: b

Explanation: The quad function is pertinent for low accuracy problems. The quadl function is more useful for high accuracy problems.

7. Double integration of a function can be done by using the _____ command.

a) int)

b) int’)

c) quad)

d) cannot be done

Answer: a

Explanation: A function, as an input to the quad command, should be within a string argument. The int command cannot take string arguments. Hence, we can use the command int) to find the double integral of a function.

8. How will ∫ e x ⁄ x look like, in MATLAB?

a) Infinite series

b) expint

c) ei

d) Error

Answer: c

Explanation: The integration of the given function is stored in MATLAB as ei or exponential integration of x. This yields a solution of an exponentially increasing series. Hence, even though it becomes an infinite series, it will be represented as ei whenever we come across such an integration.

9. The class of the result of an indefinite integration is always _____________

a) Signed

b) Double

c) Array

d) Symbolic

Answer: d

Explanation: Since we are doing indefinite integration, the result is not a number. It will contain the particular integral after integrating the function and it will only consist of the independent variable. Hence, it’s class will be symbolic.

10. The quad command cannot do ______________

a) Low accuracy integration

b) Definite integration

c) Any integration

d) Indefinite integration

Answer: d

Explanation: The quad command is used to find the integral solution for low accuracy cases. It can only do definite integration. It cannot do any indefinite integration; for that, we need the int command.

11. The function, as an input to the quad command, is given as _______________

a) Symbolic argument

b) String argument

c) Double argument

d) Rational argument

Answer: b

Explanation: The in-built operation of the quad command demands the function to be given input as a string argument. We have to write it within a pair of single inverted commas. We can use the symbolic argument for the int function while finding the definite or an indefinite integration.

12. The output of int and quad is ________

a) Same

b) Different

c) Maybe different

d) Error

Answer: b

Explanation: The output for int will be 26/3. The output for quadPrime causes double exponent: use braces to clarify is 8.6667. Hence we find that each output will be different. The int command will return a fractional form while the quad command will return a decimal form up to 4 places of decimal, rounded up to the 4 th decimal place.

Output:

For int: 26/3

For quadPrime causes double exponent: use braces to clarify : 8.6667

13. The command to get more accurate solution for definite integration is ______________

a) int

b) quad

c) quadl

d) not present in MATLAB

Answer: c

Explanation: The quadl command is used to get a result for definite integration with more accuracy. The quad command does the job with less accuracy. The int command returns fraction form and not a decimal form hence we cannot compare accuracy with it.

14. Can we do Vector integration in MATLAB?

a) Yes

b) No

c) In some cases

d) Only single integral

Answer: a

Explanation: We can do vector integration in MATLAB. We simply need to integrate the co-efficient of the vector in a certain direction with respect to an independent variable. Henceforth, we can do many applications of Vector Calculus.

15. We cannot find the integrator, made with an OP-amp, response using the quad command at steady state.

a) True

b) False

Answer: a

Explanation: The integrator circuit integrates the input waveform within a given time limit. Hence, to find the response of the integrator, we can use the quad command since it computes definite integration only. But if we want to find the steady state response, we cannot do it using quad since it does not compute for an infinite limit. Hence, we have to use the int command.

This set of MATLAB Interview Questions and Answers for Experienced people focuses on “Integration – 2”.


1. How will we integrate a non-linear function, f, taken as an inline function?

a) int

b) quad

c) quad

d) quad

Answer: d

Explanation: The function, f, will be taken as a string input. Hence, we cannot use the int command since it takes symbolic arguments while the class of our function is inline. Since the function is non-linear, we need to introduce it as a matrix to our quad command. It takes string arguments so the correct answer should be quad.

2. The correct way of using the quad command while integrating an inline non-linear function is ___________

a) quad

b) quad

c) quad

d) quad

Answer: a

Explanation: The inline function, being a non-linear function and saved as an inline class, will be given as a string argument to the quad command. Due to its non-linear nature, it has to be placed like a matrix. quad will only take the function but the function is non-linear so it will show an error. quad is wrong because the ‘’ should comprise the entire function, hence it should be outside []. quad is syntactically wrong.

3. What is the class of the result of quad command?

a) Long

b) Short

c) Double

d) Unsigned

Answer: c

Explanation: The class of the result of quad command is double. This is an in-built command in MATLAB and it will give the answer in the format double.

4. What is the output of the following code?


s=23;p=90;z=p-s;int(x^-exp(-Inf),p,z)

a) -23

b) 67

c) 0

d) Error

Answer: d

Explanation: We need to declare x as a symbolic variable before using it in the int command. The input argument to the int command should be symbolic. The answer would be -23 if we had declared symbolic before using the int command.

5. The int function returns a constant of integration for indefinite integration.

a) True

b) False

Answer: b

Explanation: The int function does not return a constant of integration after doing indefinite integration. It will only show the particular integral after integrating the input function.

6. The answer for indefinite integration in MATLAB is __________

a) The only possible particular integral

b) One of the many possible integrals

c) 0

d) erroneous

Answer: b

Explanation: Indefinite integrals can have many possible solutions. Only of the solution is provided by the int function.

7. What is the output of the following code?


int(int(x^2))

a) x^4/12

b) x^4/16

c) 0

d) Error

Answer: d

Explanation: We have to give symbolic arguments to our int command. Since we have not declared x as symbolic, the result of the int command will be an error. If the ‘x’ was declared as symbolic, the result would’ve been x^4/12.

8. We cannot perform problems regarding area under a curve in MATLAB.

a) True

b) False

Answer: b

Explanation: We can do problems pertaining to finding the area under a curve in MATLAB. This is because methods of definite and indefinite integration are present in the form of commands in MATLAB. This makes MATLAB so versatile.

9. What is the class of the result of quadl command?

a) double

b) short

c) long

d) symbolic

Answer: a

Explanation: The class of the result of quadl command is double since it computes definite integrals only. We would get the result as symbolic if we compute indefinite integration using the int command.

10. To find the particular integral of a differential equation, we use the _____

a) int command

b) quad command

c) ODE solver

d) Depends on the differential equation

Answer: d

Explanation: We can find the particular integral for the differential equation dy ⁄ dx =5x by using int. We would need an ODE solver when the differential equation is long and has multiple orders. Hence, it depends on the differential equation, how we want to select our command.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Limits – 1”.


1. Can we check the continuity of a function in MATLAB?

a) Yes

b) No

c) Sometimes

d) Rarely

Answer: a

Explanation: With the help of the limit function, we can check the left-hand limit and right-hand limit for a function approaching a limiting value. We can also check the value of the function at the limiting value. Thus, we can check the continuity of a function at the limiting value.

2. What is the output of the following code?


limit(x^2,x,1,’left’)

a) 1

b) 0

c) x should be declared symbolic

d) Cannot be determined

Answer: c

Explanation: We haven’t initialized x as a symbolic variable. But the command limit requires an argument which will initialize the function variables as symbolic. We have given x as an input to our command but we haven’t declared it as a symbolic variable. Hence MATLAB will show an error. If we had written syms x, the answer would have been 1.

3. What is the error in the following code?


limit(x^2,y,1,'left')

a) The function

b) The symbolic argument

c) Left should’ve been without

d) No error

Answer: b

Explanation: Our function does not have the character y. Hence, when we introduce y as an argument, MATLAB will show an error. If we had written limit- the answer would’ve been 1.

4. How can we check whether the lim n→3+ n-1 exists?

a) limit

b) syms n;limit

c) syms n;limit

d) syms n;limit

Answer: b

Explanation: We have to give our symbolic argument before our limit command. Hence, syms n;limit has the right order, and not syms n;limit. syms n;limit is not same as limit since there we are calculating the value of the function at the limiting value, 3, but we need to find it at the right-hand side of the limiting value- plus, limit does not declare n as symbolic- this will give an error. syms n;limit will give an error since the symbolic argument is not provided into the command.

5. What is the output of the following code?


syms n;limit(n-1,n,Inf,’right’)

a) Inf

b) Nan

c) 0

d) Error

Answer: d

Explanation: We cannot approach the limiting value Infinity from the right-hand side. So, MATLAB will return an error while trying to run the code. The answer would have been Inf if the limiting value was approached from the left hand side.

6. What is the output of the following code?


syms n;limit(n-1,n,nan,'left')

a) 0

b) Inf

c) Nan

d) Error

Answer: c

Explanation: Nan in MATLAB signifies Not a number. If we give Nan as a limiting value argument to our limit command, it will not give an error. Instead, it will return Nan as the result. The result is not helpful at all. The result would have been 0 if the limiting value was 1.

Output: Nan

7. What is the output of the following code?


syms x;limit(((1-cos(x))/(x^2)),x,0)

a) 0

b) 1 ⁄ 2

c) Error

d) Infinite

Answer: b

Explanation: matlab-questions-answers-limits-1-q7

8. What is the output of the following code?


syms x;limit(((1-cos(x))/(x^2)),x,Inf)

a) Inf

b) 0

c) Nan

d) Error

Answer: b

Explanation: matlab-questions-answers-limits-1-q8

9. What is the output of the following code?


syms x;limit((((Inf*x)-cos(x))/(x^2)),x,0)

a) limit

b) Inf

c) Nan

d) Error

Answer: a

Explanation: We observe that the numerator is Infinite and the denominator tends to 0. Hence the function is of the form ∞/0. This is an inbuilt form in MATLAB and MATLAB returns option a whenever it faces such a function. The result is of symbolic class.

Output: limit

10. What is the output of the following code?


limit(0/0, x, 0)

a) Nan

b) Inf

c) 0

d) Error

Answer: a

Explanation: The 0/0 is an indeterminate form. MATLAB will return a Nan if it comes across an indeterminate form.

11. If a function is differentiable, the function is continuous.

a) True

b) False

Answer: a

Explanation: If a function is differentiable, it should be continuous in the domain where it is differentiable. This is because if the function is not continuous, within a range, it cannot be differentiated within that range.

12. What is the code to solve lim x→1  logx ?

a) syms x;limit^)’,x,1)

b) limit^)’,x,1)

c) syms x;limit^),x,1)

d) Cannot be solved

Answer: c

Explanation: We should not give the function as an input to the limit command as a string. It will generate a warning but gives an output. We have to declare our variables as symbolic before placing our function as an argument to the limit command.

13. What is the output of the following code?


sym x;limit(log(x)^(log(x)),x,1)

a) Error

b) 1

c) 0

d) Cannot be defined

Answer: a

Explanation: When we declare a symbolic character, we use syms. If we use sym, the symbolic character is assigned to the variable ans. So, we haven’t defined x as symbolic; we have defined ans as a symbolic character which points to the character x. So, MATLAB will give an error because it cannot find x as a symbolic character. If we change the code to sym x;limit^),x,1); the answer would be 1.

14. What is the output in the following case?


syms x; limit(sin(x)/x)

a) 0

b) 1

c) Error

d) garbage value

Answer: a

Explanation: If we do not give a limiting value to our limit command, the default limiting value will be taken as 0. Hence, the output of the following code will be 1.

15. What will be the output of the following code?


sym x;limit(‘log(x)^(log(x))’,1,’right’)

a) Error

b) 0

c) 1

d) Nan

Answer: a

Explanation: While calculating left-hand limits or right-hand limits, we need to give our symbolic input as an argument to our limit command. This is an inbuilt command so we will have to follow the syntactical constraints while doing such problems.

This set of MATLAB test focuses on “Limits – 2”.


1. What will be the output of the following code?


syms x;limit('(sin(x)/x)',x,Inf,'left')

a) 0

b) Nan

c) Inf

d) 1

Answer: a

Explanation: We will get a warning since we have given our function as string input to our limit command. But the output will be 0. This is because as x approaches infinity, the function will approach zero because sin has a finite value though we are not sure of the value it still is a finite value.

Output: 0

2. What will be the output of the following code?


sym x; limit(ans^2\sin(ans),Inf)

a) 0

b) Error

c) Nan

d) Cannot be determined

Answer: a

Explanation: When we declare a variable with the sym command, the carriable is assigned to ans variable and it is a symbolic variable. Hence we can use ans as our variable which points to the symbolic variable x. Now we see the ‘ \ ‘ operator which will divide the operand on the left-hand side by the right-hand side. Hence, the output will be 0. The output is a specific number hence it will not be Nan.

3. The condition for removal discontinuity is ____________

a) Left hand limit = right hand limit ≠ function value

b) Left hand limit ≠ right hand limit = function value

c) Right hand limit ≠ left hand limit = function value

d) Left hand limit ≠ right hand limit ≠ function value

Answer: a

Explanation: The condition of removal discontinuity is given by option Left hand limit = right hand limit ≠ function value only. Rest are incorrect because the two conditions of removal discontinuity is lim n→n0 f < ∞ and f < ∞. So the function should have equal values while reaching the limiting value from both directions and it should have a finite value at the limiting value. But since there is a discontinuity at the limiting value, the values after approaching the function from both directions is not equal to the function value at the limiting value.

4. Can we perform infinite series summation in MATLAB?

a) Yes

b) No

c) Cannot be determined

d) Sometimes

Answer: d

Explanation: Symbolic summations is available in MATLAB. This allows us to find sum of series expansions. We can do infinite series summation in MATLAB. We can calculate the series to n terms and then make n approaching infinity.

5. Negative limiting values cannot be applied to logarithmic functions in MATLAB.

a) True

b) False

Answer: b

Explanation: If we give negative limiting values to logarithmic functions, they will return imaginary numbers. These can be treated as solutions to such problems. MATLAB is a very powerful computing tool that can be used to solve such problems.

6. The result of the following code?


syms x;limit(sin(x)/x,Inf,’right’)

a) Error due to symbolic argument

b) Error due to direction of approach of limiting value

c) 1

d) 0

Answer: a

Explanation: MATLAB breaks the computation as soon as it finds an error. Since the first error it gets is that we haven’t given ‘x’ as a symbolic input, MATLAB will show this as an error. Had x been introduced as a symbolic argument, the error would have been in the given direction to approach the limiting value . If we had given ‘left’ instead of right, the answer would have been 0.

7. To do double limits, we can use __________

a) limit)

b) limit

c) cannot be done in MATLAB

d) lim

Answer: a

Explanation: Double limits can be done in MATLAB. This can be done by placing limits within limits as in option limit). We cannot give multiple arguments within one lim command. There is no command called lim in MATLAB.

8. What is the output of the following code?


syms x y;limit(y*x,1,x,'left','left')

a) Error

b) Error due to symbolic argument y

c) Error due to multiple inputs

d) y

Answer: c

Explanation: We cannot give multiple inputs to the limit command. Thus the above code will give this error. We know that we have give ‘y’ as a symbolic input- but MATLAB will see this error first. Hence it will give this as an error.

9. What is the output of the following code?


syms n;limit((1+1/n)^n,Inf,’right’)

a) Nan

b) Inf

c) Error

d) e

Answer: d

Explanation: We cannot approach infinity from the right hand side. Hence MATLAB will show an error. If we had given the direction as left or if we had not given any direction, the answer would have been e.

10. We cannot calculate continuity at infinity in MATLAB.

a) True

b) False

Answer: b

Explanation: We can calculate the continuity of a function at infinity. If the function is continuous, we will get a result after using the limit command. Else MATLAB will give Inf as a result.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Sums and Products – 1”.


1. We can generate the summation of a series, formed with a character, using ________

a) symsum

b) sum

c) symssum

d) int

Answer: a

Explanation: The in-built command to find the summation of a series generated due to a character is symsum. Since our function uses symbolic characters, we need to express our function within the symsum command to get the summation.

2. If the result of our summation is Infinity, what will MATLAB show?

a) Infinity

b) Nan

c) Inf

d) Error

Answer: c

Explanation: The sum function is inbuilt in MATLAB. It has been developed so that if the summation of our given series becomes infinite, it will return a Inf as an output.

3. What will be the output of the following code?


sin(symsum(k^2,1,Inf));

a) Nan

b) Inf

c) Error

d) Output is suppressed

Answer: d

Explanation: There is no error. MATLAB will first compute the expression within the sin which will yield Inf. Thereafter, sin is computed which is shown as Nan.

4. How does MATLAB get the symbolic character in the function, if it is not mentioned in symsum command?

a) It cannot

b) It uses symvar

c) It uses symsvar

d) It uses symbvar

Answer: b

Explanation: If we don’t specify our symbolic variable which is in our function, the symsum command uses the symvar command. This command returns the set of all symbolic variables present in the function. In this way, the symsum command will continue in the execution of generating summation.

5. The sum command cannot do ____________

a) Infinite summation

b) Numeric summation

c) Long summation

d) signed summation

Answer: a

Explanation: The sum command always takes the total set of numbers to add. Since we cannot define a vector which extends up to Infinity, the sum command cannot perform Infinite summation.

6. To calculate the sum of only absolute variables in a series, we use _________

a) sum)

b) abssum

c) sumabs

d) abs)

Answer: c

Explanation: sumabs is a pre-defined function in MATLAB. It will select the absolute values from a series and find the summation of those values only. sum) will convert all the values in the series to their absolute values. abs) will give the absolute value of the summation.

7. What is the output of the following code?


sumsqr([1 2; NaN 4])

a) 21

b) Nan

c) Error

d) Inf

Answer: a

Explanation: Since Nan signifies not a number, the sumsqr command will ignore it and generate the sum of squares of all the finite valued inputs. Hence, the answer is not Nan or Inf but 21. There is no error.

Output: 21

8. What is the output of the following code:


sumsqr([Inf Inf; Inf Inf])

a) Inf

b) Nan

c) 0

d) Error

Answer: c

Explanation: The sumsqr only selects those values which are finite. Since we have not given any finite input to our argument matrix, the sumsqr command will find the sum of 0 finite values. This leads to showing an output 0.

Output: 0

9. What is the output of the following code?


sumabs([Inf Inf; Inf Inf])

a) Inf

b) 0

c) Nan

d) Error

Answer: b

Explanation: The sumabs selects finite values amongst a given series. Since we have not given any finite input to our argument matrix, the sumabs command cannot find values to add up This leads to showing an output 0. It won’t show Inf in spite of the fact that abs shows Inf. There is no error.

10. To find the absolute value of the sum of squares of numbers in a series, we use_________

a) abs)

b) sumsqr

c) sumsqr)

d) abs)

Answer: a

Explanation: The command sumsqr  finds the sum of squares of finite variables in a series. If we give sumsqr), it will convert all the values in the series to absolute values so we won’t get the true sum of the series. sumsqr will only give the sum of all the values in the series.

11. We can find the mean value of a series  using _________

a) meanabs

b) mean

c) sumabs

d) sum/n

Answer: b

Explanation: The mean command is an inbuilt command which can be used to compute the mean of n no. of values in a series. meanabs will take the sum of absolute values in the series while sumabs only computes the sum of absolute values in the series.

12. We can find the summation of an A.G.P. series using __________

a) sum

b) symsum

c) Depends on the series

d) Cannot be done

Answer: b

Explanation: If the A.G.P. series can be represented as a summation of a function, we can use the symsum to find the summation of the series. This is why MATLAB is very versatile as we can use it to reduce the time taken to solve many kinds of mathematical calculations.

13. We need to define a function separately to find the factorial of a number.

a) True

b) False

Answer: b

Explanation: MATLAB offers the prod function which may be used to find the factorial of a number. Hence, we don’t need to define a separate function to evaluate the factorial of a number.

14. The function to evaluate the following series is


12+22+32+42+52+…832

a) sqr

b) sqrsum

c) sumsqr

d) sumsqr[]

Answer: b

Explanation: sumsqr is the pre-defined function is MATLAB to evaluate such series where each element is squared. sumsqr[] is syntactically incorrect.

15. What is the output of the following code?


mean[1:10]

a) Syntactical Error

b) 4.5

c) 5.5

d) Parse Error

Answer: a

Explanation: The syntax of the mean function is mean. Now, if we give a vector input, we can either define the vector previously or we can introduce the vector itself within []. But in the given code, we haven’t placed the vector within . Hence the answer won’t be 5.5 but a syntactical error will be shown.

This set of MATLAB Quiz focuses on “Sums and Products – 2”.


1. What is the output of the following code?


meansqr(NaN)

a) 0

b) NaN

c) Error

d) 1

Answer: a

Explanation: The fuction meansqr returns the mean of the square of all finite value inputs. Since NaN is not a finite valued input, there are no other finite valued elements in the input. Hence the result is 0.

Output: 0

2. What is the output of the following code?


meanabs(1,2,-1)

a) 1.33

b) 1

c) 0

d) .666

Answer: a

Explanation: The meanabs function converts every input element to it’s absolute value and then evaluates the mean. Hence the absolute vlue of -1 becomes 1 and the final mean is 4/3 or 1.333.

Output: 1.33

3. What is the output of the following code?


A=[1:3:7;2:3:8;3:3:9]; prod(A,1)

a) Error

b) 6 20 504

c)


    6

    20

    504

d) 28 80 162

Answer: b

Explanation: prod suggests that all the elements of every column are to be multiplied and the result is going to be displayed as a row vector. Hence option c is not correct. Option d would be the transpose of prod.

Output: 6 20 504

4. What is the output of the following code?


prod(1:NaN)

a) 0

b) 1

c) NaN

d) Error

Answer: c

Explanation: The range, we have defined, from 1 consists of NaN. The product of any number with NaN will give an output NaN. Hence, the answer is option c. There will be no error.

Output: NaN

5. What is the output of the following code?


cumsum([1,2,3,4,NaN])

a) 1 3 6 10 NaN

b) NaN

c)


    1

    3

    6

   10

  NaN

d) Error

Answer: a

Explanation: The function cumsum would return the cumulative sum of every input element. Since the first 4 elements can be summed, the output will be shown but since the last element is a NaN, the final element will be a NaN. There won’t be any error due to the NaN element and option c is the transpose of option a but cumsum returns a row vector.

Output: 1 3 6 10 NaN

6. What is the output of the following code?


cumsum[NaN]

a) NaN

b) 0

c) Error due to NaN

d) Syntactical Error

Answer: d

Explanation: The cumsum function accepts inputs within parentheses. Since we have only placed the NaN as a vector element, but not within parentheses, the result will be an error. NaN won’t give an error, the result would’ve been NaN if it wass given within parentheses.

7. The product of a set of elements is always greater than it’s the cumulative sum.

a) True

b) False

Answer: b

Explanation: For the set of elements [1,2,-4,2], the cumulative sum becomes 1,3,-1,1 while the product is -16 which is less than 1. Hence, the given statement is false.

8. The function to find the R.M.S value is __________

a) sqrt)

b) sqrt[meansqr[]]

c) sqrt

d) sqrt[meansqr]

Answer: a

Explanation: The correct syntax of the function which performs the mean square of a set of elements is meansqr. The correct syntax of the function which return the square root of a number is sqrt. Hence, option sqrt) is only syntactically correct while the rest of the options are syntactically incorrect.

9. What is the output of the following code?


A=[1:3:7;2:3:8;3:3:9]; prod(A,2)’

a) 28 80 162

b)


    20

    80

    162

c) Error

d) NaN

Answer: a

Explanation: prod would’ve returned option b since giving an input 2 as a dimension sgugests that all the elements in each column are to be multiplied and the result is a single column vector consisting of the product of every element in a row. Since we have added a transpose at the end, the answer is option a. There is no Error.

Output: 28 80 162

10. Which function does cumulative summation of elements?

a) sumcum[]

b) sumcum

c) cumsum[]

d) cumsum

Answer: d

Explanation: The correct syntax for the function which does cumulative summation is ‘cumsum’. Hence option cumsum[] is wrong. The functions in options sumcum and sumcum[] do not exist in MATLAB.

11. What is the output of the following code?


cumsum(1,2,-1)

a) 1 3 2

b) 2

c) Error due to input

d) Error due to syntax

Answer: c

Explanation: We cannot give a negative number as an input to our cumsum command. This is forbidden in MATLAB and hence the error is due to input.

12. The sum function will return a NaN if any of the element in the input vector is NaN.

a) True

b) False

Answer: b

Explanation: We can write ‘omitNaN’ within the sum function so that while computing sum, the function ignores every NaN element present within the input vector.

Eg: A=[1,2,NaN];sum- This will return 3 as answer.

13. The result of cumsum and sum are ____________

a) Same

b) Different

c) Absolute numbers

d) Signed numbers

Answer: b

Explanation: The result of cumsum is 1,3,6 i.e the result is a row vector having output after adding up each element cumulatively while the result of sum is only 6. Hence, the two answers are different.

14. What is the output of the following code?


syms a,k; symsum(a^k, 1, Inf)

a) Error

b) -1/ -1

c) -1/

d) Inf

Answer: a

Explanation: We tried to define a and k as symbolic but we’ve placed a ‘ , ‘ after a. So, k never gets defined and hence the output of the symsum function gives an error since k is not defined. If there was no comma, the result would’ve been 1/ -1 while, if the code was symsum, the answer would’ve been -1/.

15. What is the output of the following code shown?


syms a k; symsum(a^k, 0, Inf)

a) 1/1-a

b) Inf

c) Error due to Inf

d) Error due to an unmentioned value of a

Answer: a

Explanation: MATLAB will return an answer intuitively while considering symbolic summations. Here, MATLAB will return an answer which is plausible to a condition. Hence it will give option a, and will also supply the condition for the answer i.e abs<1.

Output: piecewise < 1, -1/)

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Default Variables”.


1. What is the output of the following code?


q=0;syms p,q

a) q=0

b)


   p

   q=0

c)


    p

    q

d) Error

Answer: b

Explanation: The scope of the syms command ends when the input is a comma or a semi-colon. q is already declared to 0. q is not taken input as a symbolic variable. There would’ve been an error while trying to define q after a comma but it does not occur since it was already declared as an integer variable.

Output:

   p

   q=0

2. What is the default variable while evaluating a transfer function?

a) s

b) p

c) z

d) Any

Answer: a

Explanation: The MATLAB evaluates the transfer function according to the basic definition of a transfer function. So it represents a system in the frequency domain where the frequency is defined by ‘s’.

3. What is the default variable while evaluating a Laplace transform?

a) s

b) t

c) Any

d) l

Answer: a

Explanation: If no variable is specified within the laplace command, the function gives the laplace transform of the input function with ‘s’ as the independent variable. Hence, s is correct.

4. The output of the following code is


laplace(exp(-3*t),p)

a) Error due to p

b) 1/

c) 1/

d) Error due to t

Answer: d

Explanation: The input to the laplace command has to be a function which has been already declared. Hence MATLAB returns an error for this code since the t is not defined previously. It wouldn’t give an error on p.

5. The output of the following code is


solve(‘w+z=0’)

a) -z

b) -w

c) Error

d) No such fuction

Answer: a

Explanation: The default variable in MATLAB is x. Since w is nearer to x than z, the command will return a solution for w since we haven’t specified the variable who’s solution we seek. Hence, the answer is –z.

6. The default variable in case of solve’) command is __________

a) x

b) Variables near to x

c) Variables away from x

d) No default variable

Answer: a

Explanation: Unless specified, the solve command would take x as the default variable who’s solution is being sought. If the function did not have x as an independent parameter, the default variable would’ve been variables near to x.

7. What is the default parameter for dsolve command?

a) t

b) No default parameter

c) Input differentiating variable

d) Defined input parameter

Answer: c

Explanation: The dsolve command returns a solution which is parameterized by the variable that has been used as a differential in the input function. As such, there is no default variable for this command.

8. What is the default parameter for the ztrans command?

a) z

b) w

c) s

d) no default parameter

Answer: a

Explanation: The default parameter for the given command is z. This is a pre-defined command in MATLAB and uses the basic definition of the Z-transform to evaluate the result.

9. What is the output of the following code?


syms t; laplace(exp(-3*t),y)

a) Error

b) 1/

c) 1/

d) 1/

Answer: a

Explanation: y hasn’t been defined as symbolic. The output of the laplace transform won’t be derived since their will be an error. If we specify a desired variable, we have to declare it as symbolic before giving it as an input to our laplace command.

10. The default variable, to which the result of any computation.

a) True

b) False

Answer: a

Explanation: Any result is assigned to the variable ans in MATLAB. If we specify a different variable, it will be assigned to that variable.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Fourier Analysis and Filtering – 1”.


1. Butterworth and Low pass filters use _________

a) IIR and FIR Design

b) FIR and IIR Design

c) FIR Design

d) IIR Design

Answer: a

Explanation: Butterworth filters are made using the IIR Filter Design technique while Low Pass Filters are made using the FIR Design technique. Now, Butterworth low pass filters can be made using the IIR Design Technique. But the kind of low pass filters.

2. The result of the following code is


p=dtft([1,2,3],3)

a) Returns a 3-point D.T.F.T.

b) Returns a N-point D.T.F.T.

c) Returns a 3-point D.F.T.

d) Error

Answer: d

Explanation: There is no function called dtft. The command is fft which uses the fast Fourier Transform Algorithm and get the 3 point D.F.T. of the above matrix.

3. The above command will give


A=fft((1,2,3),2)

a) D,F,T after taking a truncated input

b) Yield a 2-point D.F.T.

c) Uses the Butterfly algorithm

d) Error

Answer: d

Explanation: The process of the fft command includes the operations mentioned. The syntax, in this case, is wrong since the input vector is given in parentheses. The input vector has to be placed within [].

4. The fir1 command can be used to find _____________

a) High Pass Filters using IIR method

b) Low Pass Filters FIR method

c) Filters using Window Method

d) FIR filters using Window Method

Answer: d

Explanation: The fir1 command is a pre-defined command in MATLAB and it uses the Hamming Window method to obtain the Response of any FIR filter. Low Pass Filters FIR method would’ve been correct but FIR filters using Window Method is a more generalized answer.

5. The multiplication of two signal in time domain signifies _______

a) Convolution in time domain

b) Convolution in frequency  domain

c) Multiplication in frequency  domain

d) Nothing

Answer: c

Explanation: The fourier transform can be used to find the multiplication of two signals in time domain. The convolution of two signals in frequency domain is same as the multiplication of two signals in time domain.

6. The window function is used to __________

a) multiply it with the incoming signal

b) add it with the incoming signal

c) subtract it from the incoming signal

d) divide the incoming signal

Answer: a

Explanation: The rectangular window function is multiplied with the incoming signal so that the unrequired components can be filtered out from the signal. This is the basic principle of filtering.

7. The output of the following codes are


i fft([1,2],2,2)

ii. fft([1,2],2)

a) same

b) different

c) I will give error

d) ii wil give error

Answer: a

Explanation: The result of i is a 2 point DFT of the input vector but it treats the input vector as a matrix and returns the DFT of the elements of the matrix row-wise. Hence, there is only one row which is the vector itself. Hence, the results of both codes will be same.

8. The butter command takes in ________

a) Stopband attenuation

b) Order of the filter

c) Ripple frequency

d) Nothing

Answer: b

Explanation: The butter command is used to generate the filter co-efficient of a Butterworth filter. This is done by giving the order of the filter and the cut-off frequency as input to the butter filter. The ripple frequency and the stopband attenuation is given to the buttord function.

9. The blackmann command returns a ___________

a) N-point periodic blackmann window

b) N+1-point periodic blackmann window

c) N+1-point periodic blackmann window

d) N-point symmetric blackmann window

Answer: d

Explanation: Unless mentioned, the default type of blackmann window generated by the blackmann command is a symmetric one. It is an N-point symmetric blackmann window and hence the rest of the options are incorrect.

10. The result of the following command is


hamming[32]

a) Error

b) A 32 point symmetric Hamming Window

c) A 33 point periodic Hamming Window

d) A 33 point Hamming Window

Answer: a

Explanation: There is syntactical error in this code. The input to the hamming command has to be within a pair of parentheses. Hence, the above code will give an error.

11. fft2 returns _________

a) a 2-d matrix

b) a 2-d D.F.T

c) a vector

d) No such command

Answer: a

Explanation: fft2 will return a 2-D D.F.T. of the vector given as an input to the command. It won’t give a 2-d matrix but a vector only.

12. What is the function of the unwarp command?

a) Generate smoother phase plots

b) Generate smoother gain plots

c) Generate smoother root locus

d) No such command

Answer: a

Explanation: The functioning of the unwrap command is based on the tolerance limit, ‘pi’, which is used to multiply the input vector with 2*pi so that it can return values for a smoother phase plot. Hence, Generate smoother phase plots is correct.

13. The default tolerance of the unwarp function is ________

a) pi

b) 2*pi

c) pi/2

d) 0

Answer: a

Explanation: The default tolerance value for which the unwarp function changes the elements of the input vector is pi. It can be changed by mentioning the tolerance value separately in the command.

14. The hamming command returns a ___________

a) matrix

b) row vector

c) column vector

d) no such command

Answer: c

Explanation: The hamming code returns the L point hamming window as a column vector. Hence, column vector is correct.

15. What is the value of N while creating a 27 point Hamming window?

a) 28

b) 26

c) 14

d) 13

Answer: b

Explanation: An L-point window is created with L=N+1. Hence, for a 27 point window, the value of N is 26. The rest of the options are incorrect.

This set of MATLAB MCQs focuses on “Fourier Analysis and Filtering – 2”.


1. What is the output of the following code?


buttord[2,1,3,4]

a) Error

b) Returns order of the filer

c) 1

d) 0

Answer: a

Explanation: The input to the buttord command should be given within parentheses. Since we have used third brackets, MATLAB will generate an error.

2. What is the output of the following code?


Buttord(1,2,3,4)

a) 1

b) Syntactical Error

c) Frequency Error

d) Error

Answer: c

Explanation: The passband frequency should be in the interval 0 to 1. Hence MATLAB returns an error when we give 2 as the passband corner frequency.

3. The order of the type 1 Chebyshev filter is obtained from the ________

a) cheb1ord

b) chebord

c) chebyord

d) chebshev

Answer: a

Explanation: The cheb1ord command is inbuilt in MATLAB. It helps to generate the order of the type-1 chebyshev filter and also it’s cut-off frequency.

4. The cut-off frequency of the type-2 Chebyshev filter is produced by the ________

a) cheby2ord

b) chebyord2

c) chebyshevord2

d) cheby2order

Answer: a

Explanation: The cheby2ord command is used to generate the order and the cut-off frequency of the type-2 Chebyshev filter. Hence only cheby2ord is correct.

5. The ellipord command is used for _________

a) FIR Filter design

b) IIR Filter design

c) Both IIR and FIR filter design

d) No such command

Answer: b

Explanation: The ellipord command is used to generate the minimum order of a filter based on certain design specifications. The specifications include cut-off frequencies, passband ripple and the attenuation factor.

6. The freqz command returns __________

a) No such command

b) A set of frequencies

c) Frequency Response

d) Phase plot

Answer: c

Explanation: The freqz command returns the frequency response of a filter. The input to the command are the numerator and the denominator polynomial.

7. The fftfilt command filters data based on ____________

a) Convolution

b) Overlap save method

c) No such command

d) Overlap add method

Answer: d

Explanation: The overlap add method is used by the fftfilt command to generate the filtered sequence. This command is only allowed for FIR filters.

8. The bilinear transformation is done by the ________

a) bilin

b) bilinear

c) no such command

d) bilineartran

Answer: b

Explanation: The bilinear command is pre-defined in MATLAB and is used to convert analog filters to digital filters with the help of the bilinear transformation. Hence, only bilinear is correct.

9. The bilinear command returns column vectors.

a) True

b) False

Answer: b

Explanation: The bilinear command returns row vectors. They comprise of descending powers of z of the numerator and denominator polynomial.

10. In chebwin, what is the default value of r?

a) 150 dB

b) 90 dB

c) 100 dB

d) 110 dB

Answer: c

Explanation: The default value of r is 100dB. R is the amount by which the the Fourier Transform of the side-lobe magnitude should be below the main-lobe magnitude.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Random Number Generation”.


1. What is the output of the following code?


T=rand + i*rand

a) A complex number whose real and imaginary parts are whole numbers

b) A complex number whose real and imaginary parts are fractions

c) A complex number whose real and imaginary parts are in the interval 

d) A complex number whose real and imaginary parts in the interval [0,1]

Answer: c

Explanation: The rand function generates numbers in the interval . Hence, the complex number whose real and imaginary parts are in the interval is correct. A complex number whose real and imaginary parts in the interval [0,1]would’ve been correct if the command randi was used.

2. What is the output of the following command?


randi(10 5,3)

a) Error

b) A 5*3 matrix of random numbers

c) A 5*3 matrix of random numbers in the interval [1,10]

d) A 583 matrix of random numbers evenly spaced in the interval [1,10]

Answer: a

Explanation: The above command is syntactically incorrect. A 5*3 matrix of random numbers in the interval [1,10] would’ve been the correct option if the code was randi but one comma is missing between 10 and 5. This will give an error in MATLAB.

3. What is the output of the following code?


rng(‘shuffle’)

a) Control the random number generator

b) Control the filter design process

c) Control the IIR design process

d) Control the FIR design process

Answer: a

Explanation: Commands like rand, randi use the random number generator to generate the random numbers. This can be controlled by using the rng command. The above command does not generate a result in the command window but it changes the working of the rand command.

4. The randn command generates random numbers by following a _________

a) Normal distribution

b) Normalized Normal Distribution

c) Uniform Distribution

d) Bernoulli’s Distribution

Answer: b

Explanation: The Normalized normal distribution is used to generate random numbers random numbers using the randn command- this is the inbuilt working of the randn command. Hence, Normalized Normal Distribution is correct.

5. The output of the following code


randn[(3,4)]

a) Error

b) A random set of numbers from the normalized normal distribution

c) A random set of numbers from the range 3,4

d) A random set of numbers from the normal distribution ranging from 3 to 4

Answer: a

Explanation: The above command is syntactically incorrect. The input to the randn command should be within parentheses.

6. What is the class of the variable r after the following code is run?


r=rand(1,4,’double’)

a) Array

b) Single

c) Double

d) Integer

Answer: a

Explanation: After the execution of the following command, r will be a 1*4 vector with a class of double. This is because we have defined the class within single inverted commas as double. R is a row vector so, and hence, it is an integer array. But it’s class is double.

7. The linspace command generates pseudorandom numbers.

a) True

b) False

Answer: b

Explanation: The linspace commands generate numbers which are equidistant from each other and contain within a closed range. Hence, they are not pseudorandom numbers and the statement is false.

8. What is the error in the following command?


randn[Inf]

a) Error due to Inf

b) Syntactical error

c) Misspelled command

d) No error

Answer: b

Explanation: The first error MATLAB sees is that there is a syntactical error. This will be the error which will pop up in the command window. Hence, the Syntactical error is correct. Error due to Inf would’ve been correct if there was no syntactical error. MATLAB returns the first error it founds.

9. The range of numbers returned by the following code is:


randperm(1,9)

a) [1,9]

b) 

c) [1,9)

d) (1,9]

Answer: a

Explanation: The randperm command would return 9 unique values with the permutation of numbers ranging from 1 to 9. The interval is inclusive of both 1 and 9. Hence only option [1,9] is correct. The rest are wrong.

10. What is the output of the following code?


randi(10,1,9)

a) 9 unique values with replacement in the interval [1,10)

b) 9 values with replacement in the interval  9 unique values with replacement in the interval 

d) 9 values with replacement in the interval [1,10]

Answer: d

Explanation: We have mentioned the desired number of values within the interval. Hence MATLAB will return only 9 values. The randi command generates random numbers within the specified interval which are not unique.

11. What is the output of the following code?


rand(2,’signed’)

a) A 2*2 matrix of signed data type

b) A 2 element vector of signed data type

c) A 2 element vector

d) Error

Answer: d

Explanation: The rand command cannot take signed as a user-defined data type. The available data types are single and double. Hence, this will generate an error.

12. What is the default return type of the rand command?

a) Single

b) Double

c) Signed

d) Unsigned

Answer: b

Explanation: The default return type of the rand command is double. It can be changed to single by giving single as a string input to the rand command.

13. The rand command is provided by the __________

a) Parallel Computing Toolbox

b) Signal Processing Toolbox

c) Symbolic Math Toolbox

d) Does not exist

Answer: a

Explanation: The parallel Computing Toolbox contains the rand command in MATLAB. The rest of the options are incorrect.

14. What is the output of the following code?


makedist(‘normal’)

a) Error

b) A normal distribution

c) A list of numbers selected randomly from the normal distribution

d) A normalized normal distribution

Answer: d

Explanation: If we don’t specify the mean and standard deviation of the normal distribution, the makedist command will generate a normal distribution which is normalized. This means the mean is 0 and a standard deviation is 1.

15. What is the output of the following code?


c=makedist(‘normal’);random(c)

a) An array of random numbers selected from the normalized normal distribution

b) Error due to makedist

c) A random number from the normalized normal distribution

d) Error due to random

Answer: c

Explanation: There is no error in the above code. Firstly, a normalized normal distribution would be generated. Thereafter, the random command would select a value from it and display it in the command window.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Sparse Matrices – 1”.


1. What is the attribute of sparse matrices?

a) sparse

b) double

c) vector

d) no attribute

Answer: a

Explanation: The attribute of a sparse matrix will be sparse while the class of the attribute is double, by default. Hence, sparse is correct.

2. What is the output of the following code?


sparse[m n]

a) A m*n all zero sparse matrix

b) A m*n sparse matrix

c) Error due to syntax

d) Error in the input

Answer: c

Explanation: There are two errors in the above code. MATLAB would return the syntactical error due to [] since there should be a parenthesis. There is an error in the input since there should be a ‘ , ‘ between m an n.

3. The nature of complex input taken by the sparse command is ______________

a) Only Imaginary part

b) Only positive imaginary part

c) Only negative real part

d) All of the mentioned

Answer: d

Explanation: The sparse command takes all kind of complex inputs. It is not biased by default.

4. Which of the following can be the space taken up by a sparse matrix?

a) .25 megabytes

b) 600 megabytes

c) .5 GB

d) 450 megabytes

Answer: a

Explanation: The sparse matrix takes extremely small space from memory which is why it is so useful. The most plausible option amongst is .25 megabytes while the rest suggest pretty large amount of memory.

5. To check whether the input matrix is sparse or not, we use the ________ command.

a) issparse

b) besparse

c) ifsparse

d) sparse

Answer: a

Explanation: The correct command to check whether the input matrix is sparse or not is the issparse command. The sparse command generates a sparse matrix.

6. A sparse identity matrix is generated by the ______ command.

a) sparseid

b) isparse

c) speye

d) idensparse

Answer: a

Explanation: The correct command to generate a sparse identity matrix is the speye command. The issparse command checks whether an input matrix is a sparse matrix. Hence speye is correct.

7. What is the command used to generate a sparse normally generated matrix?

a) sparserndn

b) sprandom

c) sprandn

d) no such command

Answer: c

Explanation: The sprandn command uses the same random number generator as that of the randn command. The rest of the commands don’t exist.

8. What is the output of the following code?


A=[1 2 0 3; 2 8 4 1; sin(Inf) 2 3 4];

P=sparse(A); nnz(P)

a) 11

b) 10

c) Error while declaring A

d) Error while making sparse matrix

Answer: a

Explanation: The number of non-zero numbers in the A vector is 11. Sin Is treated as NaN and holding a non-zero value since the range of sine is [-1,1]. There won’t be any error while declaring A or making the sparse matrix.

9. The non-zero elements in a sparse matrix are shown by the ______ command.

a) nzeros

b) nonzeros

c) notzeros

d) nozero

Answer: b

Explanation: The non-zeros command is used to get the non-zero elements present in the sparse matrix. The rest of the options are not defined in MATLAB.

10. What is the output of the following code?


A=[0 Inf/Inf 0 0; 2 9 7 0; sin(Inf) 8 0 0];

P=sparse(A);q=nmz(p); L=full(P);

a) l = a

b) l memory > a memory

c) l memory < a memory

d) l memory != a memory

Answer: a

Explanation: The full command converts a sparse matrix into it’s original matrix. The space taken up by both the matrices in the memory are same. Hence, only l=a is correct.

11. The size of the sparse matrix will be ___ the original matrix.

a) equal

b) greater than

c) less than

d) not equal to

Answer: a

Explanation: The sparse matrix stores the non-zero elements in the sparse matrix. The space taken up by the sparse matrix being very less than the original, the size of both the matrix will be same. Hence, only option equal is correct.

12. The maximum space allocated for sparse matrices is given by the ____ command.

a) maxsparse

b) sparsemax

c) nzmax

d) no such command

Answer: c

Explanation: The nzmax is the command to find the maximum space allocated for sparse matrices. The maximum space is proportional to the number of non-zero elements in the original matrix.

13. The output of the following command is


a=[1 2 3;4 0 0;3 0 9]; spy(A)

a) a graph of sparsity

b) a pattern of sparsity

c) syntactical error

d) logical error

Answer: a

Explanation: The spy command generates the sparsity pattern of the sparse matrix which might be generated from the given matrix. The output will generate a pattern in a window which shows the position of non-zero elements occupying space.

Output: matlab-questions-answers-sparse-matrices-1-q13

14. The output of the following code is:


a=[pi/2 pi 3*pi]; spy[a]

a) Suppressed output

b) A pattern of sparsity

c) Syntactical error

d) Symbolic error

Answer: c

Explanation: The input to the spy command has to be within parentheses. Due to this, there will be a syntactical error in the above command.

15. The spy command takes in multiple matrices.

a) True

b) False

Answer: b

Explanation: The spy command does not take in multiple inputs. It will show the sparsity pattern of only input vector.

This set of MATLAB Multiple Choice Questions & Answers focuses on “Sparse Matrices – 2”.


1. What is the output of the following code?


A=[0 0 0; 0 9 0; 1 2 3]; nnz[A]

a) 4

b) 5

c) 3

d) Error

Answer: d

Explanation: There is syntactical error while giving input to the nnz command. The input to the nnz command should be within parentheses and here the input is within []. If the input was given within , the output would’ve been 4.

2. What is the output of the following code?


A=[1 2 3; 32 23 26; 0 0 0]; spones(A)

a) Returns a sparse matrix with the non-zeros replaced by normally distributed random numbers

b) Returns a sparse matrix with the zeros replaced by ones

c) Returns a sparse matrix with the non-zeros replaced by fractions

d) Returns a sparse matrix with the non-zeros replaced by random numbers

Answer: b

Explanation: The spones command returns a sparse matrix with ones replaced by zeros. Hence, Returns a sparse matrix with the zeros replaced by ones is correct while rest of the options are incorrect.

Output:

ans =

 1

 1

 1

 1

 1

 1

3. The space located for the matrix generated from the spones command is _______

a) Same as a sparse matrix

b) Same as the original matrix

c) Same as an identity matrix

d) Double that of the sparse matrix

Answer: a

Explanation: The spones command also creates a sparse matrix. Hence, the newly generated matrix will have the same size as that of a sparse matrix.

4. What is the output of the following code?


A=[1 2 3; 4 5 6; 7 8 9];if( nzmax(A)==nzmax(spones(A) ) disp(‘Yeah !’)

a) No output

b) Error

c) Yeah !

d) Output suppressed

Answer: a

Explanation: There is no error in the above code. Since, the if command is not ended, no output will be generated. If the if command was ended, the output would’ve been Yeah !.

5. What is the output of the following code?


nnz(spconvert([1 2 3; 4 5 6; 7 8 9])

a) 3

b) 2

c) 1

d) 6

Answer: a

Explanation: The spconvert command converts the original matrix into a sparse matrix by only keeping memory for the elements in the columns. Since in the above matrix, there are no non-zero elements- the total space occupied by the new matrix is 3.

Output: 3

6. What is the output of the following code?


nzmax(spconvert([1 2 3; 4 5 6; 7 8 9])

a) 2

b) 3

c) 1

d) Error

Answer: b

Explanation: The matrix generated by the spconvert command consists of non-zero elements from the columns of the original matrix. Hence, 3 is correct.

Output: 3

7. A memory for sparse matrix is dedicated by the ______ command.

a) spalloc

b) sparsealloc

c) allocspar

d) no such command

Answer: a

Explanation: The spalloc command is used to allocate memory for a sparse matrix. The rest of the commands are incorrect.

8. What is the output of the following command?


spalloc(2,3, 7)

a) A 2*3 sparse matrix

b) Memory is allocated for a 2*3 sparse matrix

c) A 3*2 sparse matrix

d) Error

Answer: b

Explanation: The spalloc command will allocate memory for 2*3 matrix due to the above code. There will be no error.

9. The default number of non-zero elements which can be put into the memory allocated by the spalloc command is > 1.

a) True

b) False

Answer: b

Explanation: Even only 1 element can be put into the memory which has been already allocated by the spalloc command. Hence, the above statement is false.

10. The pattern generated by the spy command is a measure of the number of zeros in the input matrix.

a) True

b) False

Answer: b

Explanation: It is actually a pattern of the number of non-zero elements in the input matrix. Hence, the above statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Two-Dimensional Plots – 1”.


1. How can we smoothen the following graph of sin  and cos  into a circle?

matlab-questions-answers-two-dimensional-plots-1-q1

a) reduce the gap between linearly spaced elements of the dependent variable t

b) reduce the gap between elements of the dependent variable t

c) increase the gap between linearly spaced elements of the dependent variable t

d) increase the gap between elements of the dependent variable t

Answer: a

Explanation: If we reduce the gap between the linearly spaced variables of t, the curvature of sin would be clearly plotted by the plot command. Hence, the resultant curve would be a circle.

2. Which command gives a title to the graph plotted by MATLAB?

a) plot generates the title itself

b) title

c) hlabel

d) heading

Answer: b

Explanation: The title command is used to provide a title to the graph plotted in MATLAB. It can be provided from the taskbar of the window which opens due to the plot command.

3. Which command enables a title for the x-axis?

a) xlabel

b) horilabel

c) xlabel[]

d) no command

Answer: a

Explanation: The xlabel command is used to include a title to signify the x-axis of the graph plotted in MATLAB. Hence, the only correct option is xlabel.

4. Which command enables a title for the y-axis?

a) vertlabel

b) ylabel

c) ylabel[]

d) no command

Answer: b

Explanation: The command ylabel is used to name the y axis of the graph plotted in MATLAB. Hence, option ylabel is correct.

5. How can several graphs for the same function be plotted on the same window?

a) Contour plots

b) Bode plots

c) 3-D plots

d) n-D plots

Answer: a

Explanation: Contour plots allow the plot of multiple curves of the same function on different constant levels of the function. This is extremely helpful in analyzing systems.

6. What is the output of the following command?


meshgrid[x,y]

a) two x*y matrices

b) one x*y matrix

c) one y*x matrix

d) error

Answer: d

Explanation: The meshgrid command takes input within a set of parentheses. Hence, the above code will show an error since the input is given in [].

7. What is the output of the following code?


t=0:0.001*pi:pi/2;

plot(t,sin(t),*);

a) An inverted sine curve

b) A sine curve

c) A point

d) Error

Answer: d

Explanation: The Asterix, given as an input to the plot command, should be given within a pair of single inverted commas. Thus the above code will give an error.

8. What is the slope of the sawtooth waveform generated by the sawtooth command?

a) 1/pi

b) pi

c) 1/

d) 2*pi

Answer: a

Explanation: The slope of the sawtooth waveform always has a slope of 1/pi.

9. What is the period of the sawtooth waveform which is generated by the sawtooth command?

a) 2*pi

b) pi*2

c) pi

d) 3*pi/2

Answer: a

Explanation: The sawtooth command generates a sawtooth waveform which changes it’s peak from -1 to 1 in the period 2*pi. This is inbuilt in MATLAB and so the correct answer is 2*pi.

10. The command used to generate an array of arrows is ________

a) quiver[]

b) arrows

c) quiver

d) arrows[]

Answer: c

Explanation: The command quiver is used to generate an array of arrows. This command is used during plotting fields in 2-D. It is used to show the direction of strength of the field that is being plotted.

11. What is the output of the following code?


t=0:.001*pi:2*pi;

plot(cos(t),sin(t))

a) A circle

b) A straight line

c) A unit circle

d) A sinusoid

Answer: c

Explanation: The above code generates the unit circle which is used to define the z-plane. The graph is plotted between the values of cos and sin over their respective time period. It won’t generate a sinusoid or a straight line.

12. The period of sinusoidal curves can be changed in MATLAB.

a) True

b) False

Answer: a

Explanation: The sin command is defined to generate a sinusoid with a fundamental time period of 2*pi. The period of sinusoid can be changed by changing the angular frequency while giving input to the sine command.

13. The command to draw the nature of a function over a default fundamental period is _________

a) ezplot

b) plot

c) stem

d) plot3

Answer: a

Explanation: The plot, stem and the plot3 command does not have a default fundamental period, we need to define the period of x-axis. The ezplot command generates a plot of the input function over a default fundamental period. This fundamental period is [-2*pi,2*pi].

14. In the following code, what is the fundamental frequency of the sawtooth command?


f=1/50; sawtooth(2*pi*1/f*t)

a) 50

b) .02

c) 100

d) Error

Answer: a

Explanation: The input to the sawtooth command is a vector which is changing with a fundamental frequency. Here, 1/f is the fundamental frequency which 50. Hence the answer is 50.

15. The limits of the axes drawn are only specified in the command used to plot the graph itself.

a) True

b) False

Answer: b

Explanation: The axis command can be used to define the limits of the axis present on the graph that is being plotted. The x-axis of the graph would contain values according to the input to the plot/stem command but the visible part of the graph in the new window will depend on how the length of the axes are defined by the axis command.

This set of MATLAB online test focuses on “Two-Dimensional Plots – 2”.


1. Which command is suitable to change the axes of the graph plotted?

a) axes

b) axis

c) yxaxes

d) no command

Answer: b

Explanation: The axis command can be used to change the interchange the axes of a 2-D plot. This is easier than re=-writing the plot command already used or any other command to generate a 2-d plot. The rest of the options are incorrect.

2. What is the output of the following code?


ezplot(x^2)

a) No such command

b) A parabola

c) A part of a parabola

d) Error

Answer: d

Explanation: The input to the ezplot command should be given within a set of single inverted commas. Hence, the above code would give and error since the input function is not given within a ser of single inverted commas.

3. Which command can be used to generate multiple graphs in the same window?

a) hold on

b) wait

c) not possible without contour command

d) not possible

Answer: a

Explanation: The command used to hold the control to an already generated graph so that further plots can be made on the same window is hold on. The contour command is used to generate graph of the same function on different levels while the hold on command is used to generate graphs of multiple functions in the same window.

4. Inline functions can be plotted by the _________ command.

a) ezplot

b) plot3

c) plot

d) cannot be done

Answer: a

Explanation: The ezplot command takes in functions represented symbolically. The input is given as a string. So inline functions can be given as an input to the ezplot command to get a general graph of the input function.

5. Which toolbox provides the plot command?

a) Symbolic Maths Toolbox

b) Signal Processing Toolbox

c) Engineering Toolbox

d) Functions

Answer: b

Explanation: The commands in MATLAB are stored in files called toolboxes. The plot command is stored in the Signal Processing command while the ezplot command is stored in the Symbolic Maths Toolbox.

6. A power pattern for an antenna is a __________

a) 4-D plot of space and power

b) 3-D plot of space and power

c) 2-D plot of space and power

d) Nothing called power pattern

Answer: c

Explanation: The power pattern of the antenna is a 2-d polar plot of the power radiated by the antenna w.r.t theta in cylindrical co-ordinates. Hence, 2-d plot of space and power is only correct.

7. The general graph of f=0 is plotted by ______

a) ezplot

b) plot

c) stem

d) not possible

Answer: a

Explanation: A general graph of the function can be viewed by using the ezplot. If we want to define the values of a/b, we will use the plot or stem command. Hence, the answer is ezplot.

8. What is the period of square wave generated by the square command?

a) User-defined

b) pi

c) 2*pi

d) pi/2

Answer: c

Explanation: The square waves generated by the square(0 command will always have a period of 2*pi. We can change the duty cycle of the wave but the fundamental period is 2*pi.

9. What is the output of the following code?


plot(linspace[0,3*pi],square[linspace[0,3*pi]]);

a) A square wave from 0 to 3*pi

b) A square wave with 50% duty cycle from 0 to 3*pi

c) A square wave with 50% duty cycle

d) Error

Answer: d

Explanation: The input to the square command should be within parentheses. Here, we have not given the input vector with  and so MATLAB will show an error.

10. In a 2-d Plot, which command will make the axes of the graph same?

a) axis square

b) axis equals

c) axes square

d) axes equal

Answer: a

Explanation: There is no such command called axes. The command axis is used to change the axes of the graph that has been plotted in MATLAB. axis equal would’ve made the axes of equal length but axis equals has equals. axis square is the only correct option.

11. What is the output of the following code?


title(‘x^2+y^2=r^2’)

a) x 2 +y 2 = r 2

b) x^2+y^2 = r^2

c) Error

d) No such command

Answer: a

Explanation: The ‘^’ is used, in the title command, to place the number as an exponent. Hence, option x 2 +y 2 = r 2 is correct. The rest of the options are incorrect.

12. What is the output of the following code?


t=linspace(0,3*pi);p=sin(t);y=cos(t);plot(t,p,t,q);

a) Error

b) Multiple plots

c) A unit circle

d) A sinusoidal

Answer: b

Explanation: The plot command can be used to plot multiple graphs in a single window without using the hold command. The above code plots two sinusoidal curves from 0 to 3*pi. A unit circle would’ve been plotted if the plot command had only p and q as input.

13. What is the default range used by the fplot command?

a) [-5,5]

b) 

c) No default range

d) No such command

Answer: a

Explanation: The fplot command is almost like the ezplot command. It will plot the graph of y=f within an interval [-5,5] as it was defined. This default range can be changed by giving a separate vector input to the fplot command.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Three-Dimensional Plots”.


1. How can we group the elements in a 3-d bar graph?

a) Give ‘grouped’ as style input to bar3 command

b) Give ‘grouped’ as style input to bar command

c) Give ‘group’ as style input to bar3 command

d) Give ‘group’ as style input to bar command

Answer: a

Explanation: A 3-d bar graph is created with the bar3 command. The elements of each row of the input vector can be grouped together by giving a string input ‘grouped’ to the bar3 command.

2. What is the size of the z vector in a mesh if the sizes of x and y vectors are m, n respectively?

a) [m,n]

b) 

c) [m,n)

d) Independent of m and n

Answer: a

Explanation: The size of the z vector is dependent on the size of the x and vectors. The permissible size lies between [m,n] and hence [m,n] is correct.

3. What is the purpose of the figure command?

a) Opens a blank window

b) Opens a blank window to draw graphs

c) Opens a window containing axes

d) Opens a window containing grid and axes

Answer: b

Explanation: The figure command simply opens a separate blank window where new graphs are about to be plotted. It does not contain any axes or grid unless mentioned.


4. What is the range of co-ordinates obtained of the following code?

[x,y]=meshgrid(4)

a) 1:4 in x and y co-ordinates

b) 0:4 in x & y co-ordinates

c) only 4 in x and y co-ordinate

d) Error

Answer: c

Explanation: Since the input is not a vector, only one co-ordinate will be assigned to both x and y. Hence only 4 will be assigned to x and y as the co-ordinate.

5. What is the nature of z in surf?

a) Integer

b) Vector

c) Matrix

d) String

Answer: c

Explanation: The final input to the surf command, z, should be a matrix. The matrix is computed for each co-ordinate generated and given input interms of x and y.

6. What is the RGB triplet style for yellow?

a) [1 1 0]

b) [1 0 1]

c) [1 0 0]

d) [0 1 1]

Answer: a

Explanation: The RGB triplet specifies the intensity of Red, Yellow and Green for a user-specified color input to the surf command. For yellow, it is defined in MATLAB as [1 1 0].

7. What is the range of RGB triplets for the surf command?

a) [1 0]

b) [0 1]

c) 

d) (0 1]

Answer: b

Explanation: The range of RGB triplets for the surf command is pre-defined in MATLAB as [0 1]. If any other value is given as input, MATLAB will give an error.

8. What is the short name for black as input to the surf command?

a) b

b) bl

c) k

d) blk

Answer: c

Explanation: The short name for black has been defined in MATLAB as ‘k’. So to make the color black, we need to give k as input to the surf command.

9. How do we create horizontal bar graphs in MATLAB?

a) bar3h

b) barh

c) bar3

d) not possible

Answer: a

Explanation: The Bar3 command plots vertical 3-D bar graphs. The bar3h command plots horizontal bar graphs hence bar3h is correct.

10. The meshc command takes complex inputs.

a) True

b) False

Answer: b

Explanation: The meshc command does not take complex inputs. MATLAB will return an error if any such input is given.

11. colorbar command gives different color to the bar chart following their ______

a) height

b) width

c) length

d) independently

Answer: a

Explanation: The height of the bar-chart gives a measure of the data being shown. The colorbar command gives different color to the bar chart following their height.

12. The ezsurf command is present in the ___________

a) Symbolic Math Toolbox

b) Statistics and Machine Learning Toolbox

c) Partial Differentiation Equation Toolbox

d) Neural Network Toolbox

Answer: a

Explanation: The ezsurf command can be accessed from the Symbolic Toolbox. The rest of the Toolboxes does not have that command.

13. The color density of the bar-chart drawn from the bar3 command is always proportional to the height of the bars.

a) True

b) False

Answer: b

Explanation: The following statement is not necessarily true. The color density can be made inversely proportional to the height of the bars by giving the direction of color density as reverse as an input to the bar3 command.

14. A stacked horizontal bar-chart can be made in MATLAB by ___________

a) Mentioning stacked as input to the bar3 command

b) Mentioning stacked as input to the bar3h command

c) Mentioning stack as input to the bar3[] command

d) Mentioning stacked as input to the bar3h[] command

Answer: b

Explanation: The bar3h command is used to make a horizontal pie chart of a set of data. The bars can be stacked by giving ‘stacked’ as input to the command.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Customizing and Manipulating Graphics – 1”.


1. How can we introduce texts in a graph?

a) Use the text command

b) Use the plot command

c) Use the title command

d) Additional texts not possible

Answer: a

Explanation: The plot command will be to plot the graphs only. The title command is used to introduce a title outside the graph. A text can be introduced in a graph by using the text command.

2. What is the output of the following code?


t=linspace(0, 2*pi, .1*pi); plot(t,sin(t)); text[2,-2, ‘Ho !’];

a) a graph of sin

b) a graph of inverted sin

c) a graph with Ho ! written

d) error

Answer: d

Explanation: The input to the text command should be within parentheses. Here, the [] will result in an error. If a parentheses was used, the output would’ve been a graph of sin.

3. How many objects are created for 24 texts written in the graph?

a) 22

b) 24

c) 21

d) 2

Answer: b

Explanation: The text command would be created 24 objects in the memory for 24 texts added in the graph. It will be able to access those texts and edit them.

4. What is the output of the following code?


t=linspace(0:.1*pi:2*pi);plot(t,sin(t));text(0.5,1,’Ho !’,’colour’,’red’)

a) Error

b) A graph with Ho! written

c) A An inverted sinusoid

d) An inverted sinusoid with Ho written

Answer: a

Explanation: The text property added in the above code is ‘Colour’. This is the error, it should’ve been ‘color’. Then the output of the following code would’ve been A graph with Ho! written.

5.What is the output of the following code?


t=linspace(0:.19*pi:27*pi);plot(t,sin(t));text(0.5,1,’color’,’red’)

a) Error on plot command

b) Error in linspace command

c) Error in text command

d) A graph of a sinusoid with Ho ! written on it.

Answer: b

Explanation: The inputs to the linspace command are to be separated by a semi-colon. Here, MATLAB will give an error because the inputs are separated by a :.

6. What is the output of the following code?


t=linspace(0,.00002*pi,2*pi);plot(t,cos(t));text(0.5,1,'color','blue')

a) Syntactical Error due to text command

b) Input error due to text command

c) Error in linspace command

d) A graph of sinusoid with Ho ! written on it

Answer: a

Explanation: We haven’t given any string input to the text command which we want to show in the graph. Hence, MATLAB will send an error due to the text command. The rest of the code is okay.

7. What is the output of the following command?


t=linspace[0,20*pi,2*pi];plot(t,tan(t));text(0.5,1,'Ho!','color','blue')

a) Syntactical error in the text command

b) Error in input of plot command

c) Error in linspace command

d) The graph of tan w.r.t. t with Ho ! writted

Answer: c

Explanation: The input to the linspace command should be within a parentheses. Here, we’ve used [] so MATLAB will give an error.

8. What is the output of the following code?


t=linspace(0,.5,2*pi);plot(t,sin(t));text(0.5,1,'\mu Ho!','color','blue')

a) A sinusoid with µHo! written

b) A sinusoid with Ho! written

c) Error in the text command

d) A sinusoid with \mu Ho! written

Answer: a

Explanation: The interpretation of \mu is µ and hence A sinusoid with µHo! written is correct. There is no error in the text command.

9. What is the output of the following code?


t=[-10:1:10];plot(t,t), text(0,0,’Origin’,color,’blue’)

a) A ramp function with Origin written in Blue

b) A ramp function with Origin written in Blue and center left alignment

c) Error

d) A ramp function with Origin

Answer: a

Explanation: It displays a ramp function with Origin written in Blue.

10. The text given to the graphs can be made bold.

a) True

b) False

Answer: a

Explanation: The texts given to the graph can be made bold by giving \bf and the writing the text which we want to make it bold. Hence, the above statement is true.

11. The font style of the input text can be changed by the ____

a) fontname{}

b) fontstyle{}

c) fontname

d) fontname[]

Answer: a

Explanation: The desired fontname could be given in the style denoted by fontname{}, to the text command. This will change the font of the text printed in the graph.

12. What is the output of the following code?


t=[-10:1:10];plot(t,3*t), text(0,0,’Origin’,color,’blue’,’verticalalignment’,’left’)

a) A ramp function with Origin written in Blue and left alignment

b) A ramp function with Origin written in Blue

c) A ramp function with Origin written in Blue and center left alignment

d) Error

Answer: d

Explanation: The left is not the correct value for vertical alignment. The correct values are namely ‘center’, ‘base’, ‘middle’, ‘top’. Hence, the above code will only give an error.

13. The default colour of graph generated by the plot command is blue.

a) True

b) False

Answer: a

Explanation: The default color of the graph generated by the plot/stem command is blue. I tcan be changed from the plot command itself or the set command.

14. What is the output of the following command?


T=[-1:1:90];plot(T,T,’G’)

a) A green ramp function

b) Error

c) A grey ramp function

d) A ramp function

Answer: a

Explanation: There is no error in the above code. It will generate a green colored ramp function.

Output: matlab-questions-answers-customizing-manipulating-graphics-1-q14

15. What is the output of the above code?


T=[-1:1:90];plot(T,T,’-o’, 'MarkerIndices',1:6:length(T))

a) A green ramp function

b) A ramp function with y value marked at lengths of 5

c) A ramp function with y value marked

d) A ramp function with y value marked at lengths of 6

Answer: b

Explanation: The above code will plot a ramp function and mark the y values separated by 5 units from the initial value.

Output: matlab-questions-answers-customizing-manipulating-graphics-1-q15

This set of MATLAB online quiz focuses on “Customizing and Manipulating Graphics – 2”.


1. What is the output of the following code?


t=[0:.1*pi:pi];plot(t,sin(t),’MarkerIndices’,1:rms(sin(t)):length(sin(t))

a) Error

b) A sinusoid

c) A half wave sinusoid marked at interval of r.m.s. values

d) A green colored sinusoid

Answer: a

Explanation: The interval for marking cannot be fractional. It has to be an integer and hence the above code will result in an error.

2. The fill command cannot take more than ______ inputs.

a) 1

b) 3

c) 2

d) Many

Answer: c

Explanation: The fill command ca only take 2 inputs. MATLAB will return an error if more than 2 inputs are given to the fill command.

3. What is the output of the following code?


t=0:.000001:pi;x=sin(t);y=cos(t);fill(x,y)

a) An ellipse

b) Error

c) A semi-circle

d) A sinusoid

Answer: b

Explanation: One less input has been given to the fill command. The color is to be mentioned in the input of the fill command or MATLAB will give an error.

4. What is the output of the following code?


w=[0:.1*pi:2*pi];plot(w,sin(w),’ ’)

a) A sinusoid

b) A blank graph

c) Error in plot command

d) A sinusoid with a phase difference

Answer: a

Explanation: The output of the above code will only be a sinusoid. The input to within the ‘’ is empty so the default style of plotting with – will be used by the plot command.

5. What does the set command do?

a) The operation of the fill command

b) The operation of changing intervals of axes

c) The operation of the plot command

d) The operation of the figure command

Answer: b

Explanation: The set command can edit the graphics objects created in MATLAB. It cannot plot a graph hence it does not perform the operation of the plot, stem or the figure command.

6. What is the nature of the 2 nd vector input in the following command?


set( X,vector_1, vector _2 );

a) a m*n matrix where m=length

b) a m*n matrix where n=length

c) a m*n matrix where m>length

d) a m*n matrix where n>length

Answer: a

Explanation: The number of rows is equal to the number of inputs given into vector 1. The number of columns is equal to the number of elements in X.

7. A semi-log graph cannot be plotted in MATLAB.

a) True

b) False

Answer: b

Explanation: The scales of the axes can be converted to a linear and logarithmic scales with the set command. Hence, the above statement is false.

8. What is the output of the following code?


t=[-2:1:2];plot(t,t);ax=gca;ax.Xscale=’Logarithmic’;

a) Error

b) Syntactical error

c) A semi-log graph of a ramp function

d) A ramp function

Answer: a

Explanation: The Xscale property recognizes Logarithmic as a log. Hence, there is an error in the above code while assigning the x-axis logarithmic.

9. What is the output of the following code?


t=[-2:1:2];plot(t,exp(t));ax=gca;ax.Yscale=’Log’;

a) Error

b) An exponential graph

c) A logarithmic function

d) A ramp function

Answer: d

Explanation: The scale of the y-axis is changed to a logarithmic nature. But an exponential function is plotted in the y-axis and hence the graph is being approximated to a straight line which follows the interval of the input only.

10. Using the set command for axes can be replaced by setting the ___ to a variable.

a) gca

b) gcf

c) gco

d) not possible

Answer: a

Explanation: The gca is used as an object to represent the axes. The properties of the axes are contained in the gca. The gca can be assigned to a variable and now we don’t have to use the set command to edit the axes of the graph. The gcf is used to represent the graph plotted.

11. What is the output of the following code?


plot([-3:1:3],[-3:1:3]);cla;

a) Error

b) A ramp function

c) A graph of a ramp function with no axes

d) A window having two axes

Answer: d

Explanation: A ramp function was plotted due to the plot command. But the cla command removed all graphics object from the window containing the graph and hence the correct option is a window having two axes.

12. How many objects are created for 24 texts written in the graph?

a) 22

b) 24

c) 21

d) 2

Answer: b

Explanation: The text command would be created 24 objects in the memory for 24 texts added in the graph. It will be able to access those texts and edit them.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Branching – 1”.


1. Amongst multiple elseif and nested if, which would take less runtime?

a) multiple elseif

b) nested if

c) elseif

d) elseif & nested if

Answer: a

Explanation: If multiple elseif and nested if has the same number of conditions. Multiple elseif checks at each step if it at all it has to go to the next condition. But nested if checks each condition before leaving the entire control structure. Hence, the number of steps covered in multiple elseif is less than nested if. Thus the former will take less time.

2. What is the output of the following code?


if(x~=c)

p=0;

end

a) p=0

b) Output will be suppressed

c) Error

d) Cannot be determined

Answer: c

Explanation: While using relational operators on character variables, we need to use ‘’. Hence, MATLAB gives an error when we write x ~ =c. If we had placed c within ‘’, the output would have been displayed as p=0.

3. The end statement is given multiple times in _________

a) Multiple elseif

b) Nested if

c) elseif

d) if

Answer: b

Explanation: We need to end each if structure within a nested if structure every time we give one. The end command should be placed after the end of each if structure or MATLAB will give an error.

4. What will happen if we don’t give an otherwise block to our switch structure?

a) Error

b) Infinitely demands a correct variable for case

c) Returns 0

d) Moves on to the next block

Answer: d

Explanation: If we don’t give an otherwise block to our switch structure, it will not give any error. It will simply continue with the execution of statements after the switch structure.

5. What is the output of the following code?


syms x;

if(x>50)

fprintf('Error')

end

a) Error

b) Prints Error

c) Does not print error

d) Cannot be determined

Answer: a

Explanation: We have declared x as a symbolic variable and haven’t assigned any value to it. So it is not declared with 0, it is only a symbolic character. Hence, the if structure cannot check the condition because it cannot convert the symbolic form to logical form. Hence it won’t go inside the if structure- it will return an error but not print ‘Error’.

6. While developing a switch-case structure, the value for case can be _________

a) Single only

b) Multiple

c) Infinite

d) 0

Answer: b

Explanation: The switch-case structure has a versatile syntax in MATLAB. We can give many numbers of case values to match with the input. This can help us in solving complex problems where we need selection of values.

7. What is the output of the following code?


syms x c; 

if(x~=c)

fprintf(‘Error’); 

end

a) Error

b) Error due to x

c) Error due to c

d) Error due to x and c

Answer: a

Explanation: Since we declared x and c with the syms command, they have been assigned to the variable ans. Hence, matlab would have printed ‘Error’. The output won’t be suppressed.

8. What is the output of the following code?


sym x c; 

if(x~=c)

fprintf('Error');

end

a) Error

b) Error due to x

c) Error due to c

d) Output suppressed

Answer: b

Explanation: Since we have used the sym command, x and c will be declared symbolic but they will be assigned to a separate variable. Hence, MATLAB will show an error since it can find the symbolic variable x. If we had used the syms command, MATLAB would have printed ‘Error’. The output won’t be suppressed.

9. Menu-driven architecture should be done by ________

a) if-else structure

b) switch-case structure

c) stack

d) loop structure

Answer: b

Explanation: A Menu implies that we have sections. A switch-case structure offers sections or cases which will be implemented based on the switching value. Hence, this is perfect for a menu-driven architecture.

10. The program to check the highest of n numbers can be done by ________

a) Sorting

b) If-else structure

c) Switch-case structure

d) Depends on the nature of n

Answer: a

Explanation: The sorting procedure is the easiest way to get the highest of n numbers. This is because the code complexity will increase, drastically, if we use an if-else structure or a switch-case structure.

11. Giving conditions using characters, we give them using ____

a) ‘’

b) ””

c) No special character

d) []

Answer: a

Explanation: The ‘’ is used while dealing with characters. If we haven’t declared our characters before using them, we can compare characters by placing them within ‘’.

12. The if structure is a _________

a) Conditional structure

b) Logical structure

c) Nested structure

d) Biased structure

Answer: a

Explanation: The steps of execution in the if structure follows a hierarchy of checking conditions. If the condition is not satisfied, the control breaks from the structure and goes to execute the next state of statements.

13. The switch-case structure is a _________

a) Conditional structure

b) Logical structure

c) Multidimensional structure

d) Hierarchical structure

Answer: b

Explanation: Any case in the switch structure gets executed if the switching variable and the case value satisfies the logical condition of equality. Hence the switch-case is a logical structure since based on the equality of the two values, the case will get executed.

14. What is the output of the following code?


if()

p=9;

end

a) Error

b) p=9

c) Output is suppressed but p=9

d) 0

Answer: a

Explanation: We cannot keep the condition as empty. We need to give a condition otherwise control will never proceed to allow us to design the if structure. It will show an error as soon as we hit enter after if. The output could’ve been 9 and it would’ve been suppressed due to the ‘’, but this code will show an error.

15. What is the output of the following code?


if(x=99)

var=92;

end

a) Error

b) var=92

c) Output is suppressed but var=92

d) Nan

Answer: a

Explanation: We cannot use an assignment operator in our condition statement while using an if-else structure. We have to use a relational or logical operator only.

This set of MATLAB Question Bank focuses on “Branching – 2”.


1. The if-else structure does not allow ___________

a) Return statement

b) End statement

c) Endif statement

d) Break statement

Answer: d

Explanation: The break statement is not allowed within an if-else structure, it is strictly for a loop structure. We can use the return statement and the end statement but the break statement will give an error.

2. What is the output of the following code?


if((-10 &&00)||(20134 && 900))

fprintf("%s","True.")

else

fprintf("%s","False.")

end

a) True

b) False

c) Error

d) Nan

Answer: a

Explanation: The logical && will give 0 if and only if one of the anding value is 0. So -10&&00 returns 0 but 20134&&900 gives 1. The logical || gives 0 if both the values are 0. But here, 0||1 is 1. Since the logical expression yields 1, the condition is satisfied and the output is True.

Output: True

3. What is the output of the following code?


if(1)

p=9;

end

a) p=9

b) Output is suppressed but p=9

c) Error

d) Nan

Answer: b

Explanation: The condition has no kind of operator. But we have given the value 1 as a condition. So, the condition will be taken as true and control will execute the set of statements within the if structure. Now we have placed a ‘;’ so the output will be suppressed but p=9.

4. What is the output of the following code?


num=2;

switch num

case[2 3 4]

p=9;

case[1 5 6]

q=9;

end

a) No output

b) p=9

c) q=9

d) Output suppressed but p=9

Answer: a

Explanation: When we are giving multiple values for a single case, we have to give those values within {}. Since the code contains [], the switch-case structure won’t work.

5. What will be the output of the following code?


switch num

case '2'

p=2;

case '2'

p=4-5;

end

a) p=2

b) Error

c) No output

d) p=-1

Answer: c

Explanation: We observe that we have given the same case value for multiple cases. This will not generate an error in MATLAB but the switch-case structure won’t work properly and MATLAB will not give any output.

6. Before starting a new case, we have to end the previous case using ___________

a) Break statement

b) Continue statement

c) Return statement

d) No statement

Answer: d

Explanation: MATLAB is not like C. So, we don’t have to give the break statement every time we end a case. We can write the next case and during runtime, the control will leave the switch-case structure after executing the matched case. We can give the break statement during looping and the return statement during if-else structure.

7. We cannot use a ____ statement in the standalone if-else structure.

a) break

b) if-else

c) return

d) switch-case

Answer: a

Explanation: If the if-else structure is not within any loop, we cannot use the break statement. The break statement is only allowed for loops. If the if-else structure is part of a loop, we can use the break statement to end the loop before it reaches its limit.

8. The continue statement can be used in a switch-case structure.

a) True

b) False

Answer: b

Explanation: The continue statement is only allowed for and while loops. If we give the continue statement within a switch-case structure, MATLAB will give an error.

9. We cannot use a ____ statement if the if-else structure is not part of a loop.

a) continue

b) if-else

c) clc

d) plot

Answer: a

Explanation: If the if-else structure is not within any loop, we cannot use the continue statement. The continue statement is only allowed for ‘for’ and ‘while’ loop.

10. What will be the output of the following code?


if(cos(Inf)==NaN)

p=1;

end

a) p=1

b) Output suppressed but p=1

c) Error

d) No output

Answer: d

Explanation: The condition sin==NaN is not satisfied because MATLAB knows sin has a value between 1 and -1, even though it cannot comprehend it. Hence, it will produce a logical 0 and the control will exit the if structure, it will give no output.

11. What will be the output of the following code?


switch num

case ‘a’

p=394;

case ‘b’

c=0;

end

a) Error

b) No output since we haven’t given num a value yet

c) p=394

d) c=0

Answer: a

Explanation: We haven’t declared num as symbolic. So we cannot use it as our switching value. Hence, MATLAB will give an error. It wouldn’t have generated any output since we haven’t assigned a character with num, but first it will show an error.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Logical Expressions – 1”.


1. If a logical expression is true, it will always return a logical 1 and if it’s false, it’ll always return a 0.

a) True

b) False

Answer: a

Explanation: Any logical operation is pre-defined in MATLAB to give a logical 1 if the result derived from the operation is true. If the result is false, the result returned will be a logical 0.

2. The functioning of all and any is same.

a) True

b) False

Answer: b

Explanation: The all function returns a 1 iff all the elements in the input vector is non-zero. The any function returns a 1 iff at least 1 element in the input vector is non-zero. Hence, they are different in functioning.

3. What does the function all do?

a) Returns 1 if all elements within it are 0

b) Returns 0 if all elements within it are 0

c) Returns 0 if all elements within it are non-zero

d) Returns 1 if all elements within it are non-zero

Answer: d

Explanation: The all function is inbuilt in MATLAB. If we give a vector input to our function, it will return a 1 if all the elements of the vector are non-zero.

4. What will be the output of the following code?


all([1 0])

a) 1

b) 0

c) Error

d) Nan

Answer: b

Explanation: The all function returns a logical 1 iff all the elements within the input vector are non-zero. Since, here, one element is 0- the logical output is 0.

5. Choose the correct hierarchy of operations.

a) |,&,+,-

b) +,-,&,|

c) :,+,-,&

d) |,:,&,.^

Answer: b

Explanation: Amongst the given operators, the hierarchy is [.^], [+], [-], [:], [&], [|]. Hence, the only possible option is +,-,&,|. The rest are erroneous according to the pre-defined hierarchy in MATLAB.

6. What is the output of the following code?


2++++++++9

a) 11

b) 74

c) 25

d) Error

Answer: a

Explanation: Since + is a unary operator, it won’t give an error in MATLAB. Hence, the output of the above code will be 11.

Output: 11

7. What is the output of the following code?


sin(Inf) & sin(nan)

a) Error

b) 1

c) 0

d) Nan

Answer: a

Explanation: Nan cannot be used while dealing with logical operators. Hence, the above code will give an error.

8. What will be the output of the following code?


all([Nan])

a) 1

b) 0

c) Error

d) Nan

Answer: c

Explanation: Nan is not defined in MATLAB. It should have been ‘NaN’ or ‘nan’. If it was either of them, the result would’ve been 1 since NaN is not equal to 0.

9. What will be the output of the following code?


~xor(3476,1234)

a) 1

b) 0

c) Error

d) NaN

Answer: a

Explanation: The output of xor will be 0 since xor returns a logical 1 iff one of the argument is 0. Since we have added the not operator before, the output will be 1.

Output: 1

10. What will be the output of the following code?


~or(~xor(1,1),~or(0,1))

a) 1

b) 0

c) NaN

d) Error

Answer: b

Explanation: The output of ~or is 0. The output of ~xor is 1. Hence, the output of ~or is 0.

Output: 0

11. What will be the output of the following code?


any(sin(0), NaN)

a) 1

b) Error

c) 0

d) No such function

Answer: a

Explanation: The any function returns 1 if any element, within the input vector, is non-zero. Since NaN is non-zero, the output will b 1.

Output: 1

12. What will be the output of the following code?


any(xor(1,1), ~or(xor(1,0),1), sin(pi), NaN)

a) 0

b) 1

c) Error due to too many arguments

d) Error due to NaN

Answer: c

Explanation: The all function takes a single vector as input. If we had placed all the elements within [], there wouldn’t have been any error and the output would’ve been 1. NaN won’t give any error infact the occurrence of NaN will give the output 1 or the output would’ve been 0.

13. What will be the output of the following code?


all([or(1,1), ~xor(xor(1,0),1), cos(pi)])

a) 0

b) 1

c) Error

d) No such function all

Answer: b

Explanation: The all function returns 1 iff all the elements within the input vector is non-zero. Here, xor is 1 and ~xor is 1. or is 1 and cos is -1. Thus, all the elements are non-zero.

Output: 1

14. What will be the output of the following code?


all(sin(pi), 1)

a) 0

b) 1

c) Error

d) NaN

Answer: b

Explanation: sin is not 0 since pi is just a floating point variable in MATLAB. The output of sin) would’ve been 0. Thus the output of the above code is 1 since the function all returns 1 iff all the elements of the input vector is non-zero.

Output: 1

15. The correct hierarchy of operations is ________

a) <.<=,|,&

b) >,>=,&,|

c) <,>=,|,&

d) <,|,>,&

Answer: b

Explanation: Amongst the given operators, the correct hierarchy is <, <=, >, >=, &, |. Thus the most plausible >,>=,&,| according to the pre-defined hierarchy of operations in MATLAB.

This set of MATLAB Questions and Answers for Entrance exams focuses on “Logical Expressions – 2”.


1. ‘=’ is a?

a) Relational operator

b) Arithmetic operator

c) Operational operator

d) Assignment operator

Answer: d

Explanation: p=2 assigns the value 2 to the variable p. Hence, ‘=’ is an assignment operator. It doesn’t perform arithmetic operations so it isn’t an arithmetic operator. It isn’t a relational operator unlike ‘==’.

2. What is the output of the following code?


sin(pi)~=0

a) NaN

b) 0

c) 1

d) Error

Answer: c

Explanation: sin is not equal to 0 since pi is represented as a floating point number in MATLAB. If pi was declared as a symbolic variable, the output would’ve been 0.

Output: 1

3. What is the output of the following code?


sin(Inf)~=NaN

a) 1

b) 0

c) Error

d) NaN

Answer: a

Explanation: sin is actually a number since the domain of sine is -infinity to infinity and the range is always -1 to 1. Hence, sin is still a number- but it cannot be comprehended hence the value will be returned NaN. But in the above comparison, MATLAB will observe that sin is still a number within -1 and 1 and hence, the output is 1.

4. What is the output of the following code?


log(0)==Inf

a) 1

b) 0

c) Error

d) Inf

Answer: b

Explanation: log is -Inf. This is why the output of the above code is 0.

Output: 0

5. What is the output of the following code?


and(sin(pi),112312)

a) 1

b) 0

c) 00

d) Error

Answer: a

Explanation: sin won’t return 0 since pi is an in-built floating-point constant. If we had declared pi as symbolic, the output would’ve been 0.

6. The ~ is ______

a) Quaternary operator

b) Relational Operator

c) Arithmetic Operator

d) Unary Operator

Answer: d

Explanation: ~ is a unary operator since the NOT function operates on only one operand. It isn’t a relational operator since it doesn’t do any comparison and it’s not an arithmetic operator since it doesn’t perform any arithmetic operation.

7. All logical operators operate on at least two operands.

a) True

b) False

Answer: b

Explanation: The ‘ ~ ’ operator operates on one operand but it’s a logical operator. Hence, the statement is false.

8. What is the output of the following code?


NaN==Inf

a) 0

b) 1

c) Nan

d) Inf

Answer: a

Explanation: Nan and Inf are two symbolic variables in MATLAB suggesting ‘Not a number’ and ‘Infinity’ respectively. These are not equal to each other and hence we will get a logical 0 when we enter this in MATLAB.

9. What is the output of the following code?


Sin(Inf)==NaN

a) 0

b) 1

c) Nan

d) Inf

Answer: c

Explanation: If we type sin in MATLAB, we will get NaN as an input because MATLAB cannot find the value of sin. But, MATLAB knows that sin possesses a value, it cannot comprehend it but still it has a value. So, even though it will show NaN when we write sin, it will not give a logical 1 for the following code since sin is still a number between 1 and -1.

10. The precedence of : operator is after | and before &.

a) True

b) False

Answer: b

Explanation: The hierarchy for precedence of operators for the aforementioned operators is :, &, |. Hence the given statement is false.

11. What is the output of the following code?


~xor(and(1,0),~xor(and(1,0),0))

a) 0

b) 1

c) NaN

d) Error

Answer: a

Explanation: and is 0. ~xor is 1. But xor is 1. Hence, ~xor is 0.

Output: 0

12. The precedence of Transpose operation is ____________

a) after &

b) after |

c) before .^

d) after ^

Answer: c

Explanation: The transpose operation has the highest precedence amongst all the aforementioned operators. The hierarchy is .’, .^, ^, &, |. Hence option before .^ is correct.

13. All relational operators operate on _______________

a) only real part of complex numbers

b) only imaginary part of complex numbers

c) complex numbers

d) numbers which are not complex

Answer: a

Explanation: Some relational operators do not operate on the imaginary part of the complex numbers. But all relational operators operate on the real part of complex numbers.

14. What is the output of the following code?


any([])

a) 0

b) 1

c) NaN

d) Error

Answer: a

Explanation: Since there are no elements in the input vector, it also means there are no non-zero elements in the vector. Hence, the logical result of the operation is 0.

15. What is the output of the following code?


all[1, 2, 3, NaN]

a) Error due to NaN

b) 1

c) 0

d) Syntactical Error

Answer: d

Explanation: Even though the elements were declared within a vector, the syntax of the all function is wrong since the vector should be present within a pair of parentheses. If the vector was given within a pair of parentheses, the result would’ve been 1. No error will be given due to NaN.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “More about Loops – 1”.


1. What is the output of the following code?


i=0;for i=0:2  

i=1; end

a) Output is suppressed

b) Output shows 1 3 times

c) Output shows 1 2 times

d) Error

Answer: a

Explanation: The output won’t be shown since we’ve added a semi-colon after the declaration of the variable i. If there was no semi-colon, the output would’ve been i=1, 3 times. There is no error.

2. What is the output of the following code?


i=0;for j=0:2  

j=j-1

end

a) Infinite loop

b) -1

c) Output is suppressed

d) +1

Answer: b

Explanation: The output is suppressed since there is a semi-colon after the decrement of j. The counter variable is really treated as a different variable hence the value of j at the end of the loop is not 2.

3. What is the output of the following code?


a=0;for j=0:2  

j=j+1 end

a) Syntactical Error

b) 3

c) 2

d) Keyword Error

Answer: d

Explanation: The end is a reserved keyword and it cannot be used in the same line with j+1. Hence, the for-loop will end without even beginning. The output would’ve been 3 if the end was in the next line. There is no syntactical error.

4. What is the final value of j from the following code?


for j=(0:3)  

j=j+1;

end

a) Syntactical error

b) Declaration error

c) 3

d) 4

Answer: a

Explanation: The syntax of for loop in MATLAB does not include parentheses. Here, the counter is introduced within parentheses and hence, there will be an error.

5. What is the output of the following code?


for j= 4:2   

j=j+1 

end

a) an empty vector, j

b) 3

c) 2

d) error

Answer: a

Explanation: The loop never runs since if we want to decrease the counter value, we will have to introduce the decrement value. The default form, used here, is for increment operation. Hence, the output is an empty vector, j.

6. What is the output of the following code?


for i!=1:10 

p=p+1;

a) Syntactical Error

b) Inf

c) NaN

d) Logical Error

Answer: d

Explanation: While mentioning the number of times a loop would run, we have made an error in defining the range. The above statement, really, signifies that the loop won’t run for i= [1,10]. So we did not mention, when the loop will actually run. This results in the error.

7. In nested loops, the break statement exits the ____ loop.

a) external

b) last started ongoing

c) not available in MATLAB

d) for

Answer: b

Explanation: The break statement exits the loop in which it is only called. It doesn’t care about the remaining number of iterations in the loop but it only exits from the inner loop and the control still remains in the outer loop.

8. In nested loops, the continue statement exits the ____

a) current iteration

b) loop

c) inner

d) outer

Answer: a

Explanation: The continue statement stops the current iteration and restarts a new iteration of the same loop if the condition is not matched. It does not exit from the outer or the inner loop.

9. In nested loops, the break statement, if present within a nested if the structure, will exit the _______

a) Ongoing if structure

b) Entire loop

c) Ongoing loop

d) Entire if structure

Answer: b

Explanation: The break statement will exit the loop where the break statement is present. It won’t take control out of the external loop.

10. In nested loops, the continue statement, if present within an if structure, will exit the ____________

a) If structure

b) current iteration

c) entire loop

d) Error

Answer: b

Explanation: The continue statement will only end the current iteration and it will start the next iteration. It won’t exit from the entire loop.

11. In nested loops, the continue statement, if present within a nested if structure, will exit the ____________

a) If structure

b) nested if structure

c) entire loop

d) present iteration

Answer: b

Explanation: If the continue statement is present deep-rooted in a nested if structure, it will only stop the current iteration. It won’t exit the current ongoing loop or the external loop.

12. What is the output of the following code?


for j= 4:2:2   

j=j+4 

end

a) Error

b) j=6

c) Error an empty vector, j

d) Syntactical error

Answer: c

Explanation: The counter never runs since the initial value is less than the final value but the counter value is positive. This breaks the running of the loop and the value of j is an empty vector.

13. While running a loop in MATLAB, it does not require indentation.

a) True

b) False

Answer: a

Explanation: The following statement is true for MATLAB. One may use it to make it easier to check a loop but MATLAB won’t give an error if we don’t use indentation.

14. The effective working of the continue keyword in the final iteration is same as the effective working of the break keyword.

a) True

b) False

Answer: a

Explanation: If the continue statement gets executed in the final iteration of a loop, the control breaks the loop. The break statement will exit control irrespective of the number of iterations left and hence the above statement is true.

15. The number of iterations run for any loop by MATLAB is always _____________

a) a positive integer

b) a negative integer

c) a number

d) a decimal number

Answer: c

Explanation: It is not necessary that a loop will do at least one iteration. If the condition of a while loop is not satisfied before the first iteration, it won’t iterate even once and the number of iterations is 0.

This set of MATLAB Questions and Answers for Campus interviews focuses on “More about Loops – 2”.


1. The for loop performs at least ___ iteration/s.

a) 1

b) not necessarily an iteration

c) 2

d) Error

Answer: b

Explanation: Suppose the condition given to check by the for loop has a logical error- the for loop won’t iterate even once. Hence, it is not necessary that the for loop will run even once.

2. Multiple graphs can be plotted, in the same window, if we use the ___ command in a loop.

a) hold on

b) held on

c) hold off

d) not possible

Answer: a

Explanation: The hold on command can be used to plot multiple graphs in the same window by using a loop. Hold off is used to exit the functioning of the hold on command. Hence, the correct option is hold on.

3. The number of iterations in the following loop is


p=3;for i=(3:4)

p=p+2;

end

a) 0

b) 1

c) 3

d) 4

Answer: d

Explanation: If the counter value is <= the final value, the loop will perform an iteration. Hence, the above loop iterates twice to yield p=6. There is no error.

4. What is the output of the following code?


q=0;for i=(1:1)

q=q+5;

end

a) Output is suppressed

b) Syntactical error

c) q=5

d) Declaration error

Answer: a

Explanation: The output is suppressed due to the semi-colon after q=q+5. The output of the following code would’ve only been q=5 if the output was not suppressed. There is no error in the above code.

5. What is the output of the following code?


a=0;for i=[1:1]

q=a-55;

end

a) Syntactical Error

b) Declaration error

c) Output is suppressed

d) q=-55

Answer: c

Explanation: The expression for counter can be given within [] in the for statement. The output is suppressed due to the semi-colon after q=a-55. The output of the following code would’ve only been q=-55 if the output was not suppressed. There is no error in the above code.

6. What is the nature of the error in the following statement?


for i=1:

a) Incomplete

b) Unexpected operator

c) Invalid keyword

d) No error

Answer: a

Explanation: MATLAB would recognize that the above statement for starting the for loop is incomplete. Hence, it will give the option incomplete as an error.

7. What is the nature of the error in the following statement?


for i=:1

a) Incomplete syntax

b) Unexpected MATLAB operator

c) No such keyword

d) No error

Answer: b

Explanation: The syntax of the for loop is not recognized by MATLAB. Hence, it will give the unexpected MATLAB operator as an output.

8. What is the output of the following code?


i=0; while[i<5] 

i=i+1;

end

a) Syntactical Error

b) Declaration Error

c) Output is suppressed

d) i=5

Answer: c

Explanation: There is no error due to []. The output is suppressed due to the ‘ ; ‘. The value of I stored in the workplace is i=5.

9. The condition of a while loop cannot be given in ________

a) 

b) []

c) {}

d) <>

Answer: c

Explanation: The variables of the condition gets converted to a cell format if the condition is given in {}. Thereafter, the variables cannot be converted into a logical form. It can be given within  and [].

10. What is the output of the following code?


while{i<5}

i=i+1234;

end

a) i=1234

b) Output is suppressed

c) Error in converting the cell to logical form

d) Error in i

Answer: c

Explanation: MATLAB returns the first error it finds. Now, i is not defined before using it as a variable for a condition in the while loop. But the first error is the fact that the condition is given in {} so it is in a cell format and the conversion to logical form is not possible. Hence, MATLAB will return an error.

11. What is the output of the following code?


i=0;while(i<5)

i=i-1;

end

a) Error

b) i=-Inf

c) i=NaN

d) Infinite loop

Answer: d

Explanation: The following code will start an infinite loop. The control can be broken form the loop by pressing ctrl+c.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Commands for Parsing Input and Output – 1”.


1. What is the working of the nargin keyword?

a) Returns the number of inputs to a function as an output of the same function

b) Gets assigned to a value equal to the number of inputs of a function

c) Gets assigned to a value equal to the number of inputs+1 of a function

d) Gets assigned to a value equal to the number of inputs-1 function

Answer: b

Explanation: The nargin command takes a value which is equal to the number of inputs given to the function.

2. What is the working of the varargout command?

a) Returns a 1*N cellular matrix

b) Returns a 1*N cell array of outputs

c) Returns a 1*N cell array of inputs given

d) Doesn’t exist

Answer: b

Explanation: The varargout command returns a set of output elements in a 1*N cell array. It doesn’t return the number of inputs.

3. What is the working of the nargout command?

a) Gets assigned to a number which is equal to the number of outputs-1 sought from a subfunction

b) Gets assigned to a number which is equal to the number of outputs-1 sought from a function

c) Gets assigned to a number which is equal to the number of outputs sought from a function

d) Gets assigned to a number which is equal to the number of outputs+1 sought from a function

Answer: c

Explanation: The nargout command gets assigned to a number which is equal to the number of outputs sought from a function. It will control the nature of outputs produced by the function where it is present.

4. What is the working of the varargin command?

a) takes 1*N inputs after the defined inputs in a function

b) takes N*1 inputs after the defined inputs in a function

c) takes N*N inputs after the defined inputs in a function

d) takes 1*1 inputs after the defined inputs in a function

Answer: a

Explanation: The varargin command takes 1*N inputs after the defined inputs to a function. It allows the function to take many input arguments and control the output of the function.

5. What is the output of the following command?


function s= average(varargin)

celldisp(varargin)

s=sum(varargin)

end

p=average(1:3)

a) Error in sum

b) Error using varargin in function definition

c) Error calling the average function

d)


    1 2 3

     p=6

Answer: a

Explanation: The input is acellular array called varargin. The input to the sum function in the average function is should be varargin{1} to indicate which element of the array varargin is to be taken.


6. What is the output of the following command?


function wish= ful(p,varargin)

celldisp(p)

wish=sin(varargin{1})

end

p=ful(1:3)

a) Error in calling the function

b) Error in celldisp

c) Error in the function definiton

d) Error in the wish variable

Answer: b

Explanation: p is treated to a function which takes inputs as cellular arrays. In the above code, if the input to the ful command was {1:3}, the output would have been

p{1}= 1 2 3

Hence, the error is in using celldisp command, only disp command is to be used.

7. What is the output of the following command?


function mad= heart(p,varargin)

disp(p)

wish=sin(varargin{0})

end

p=heart(1:3,0)

a) Error in wish command

b) Error while calling heart command

c) Error while calling disp command

d)


     1 2 3

     wish=0

Answer: a

Explanation: The arguments to a cell array start from the index 1. Here, varargin{0} will create an error and hence, error in wish command is correct.


8. What is the output of the following command?


function mad= rush(p,varargin)

disp(p)

wish=cos(varargin[0])

end

p=rush(1:3,pi/2)

a) Error due to element index

b) Error due to syntax of varargin

c)


  1 2 3

  wish=0

d) Error due to disp

Answer: b

Explanation: The first error MATLAB finds is that the index of the element of the varargin array is given within []. This creates the error and MATLAB returns the first error it invokes The next error is the fact that there are no elements in varargin whose index number is 0.

9. What is the output of the following code?


function mad= rush(p,varargin)

disp(p)

wish=cos(varargin{1})

end

p=rush(1:3,Inf)

a) Error due to Inf

b) -1

c)


    p{1}= 1 2 3

    wish=0

d)


     p{1}= 1 2 3

     wish=NaN

Answer: d

Explanation: There is no error due to Inf. The disp function will display 1 2 3 due to the input vector 1:3 and wish will be assigned to NaN since cos is NaN.


10. What is the output of the following code?


function maha= orchid(polo,varargin)

disp(polo)

wish=sum(varargin{1,2})

end

p=rush(-1:1,Inf)

a) Logical error in varargin

b) Syntactical error in varargin

c)


     p{1}=-1 0 1

     wish=0

d) No output

Answer: a

Explanation: Varargin is a 1*N cellular array. The index number given as input to the varargin command looks like we are calling the element in the 2 nd row and the 1 st column which is not there. Hence, there is logical error in using the varargin keyword.

11. What is the output of the following code?


function [die,absdif] = BDO(y,x)

die = y-x;

if nargout > 1

    disp('Boo !')

    absdif = abs(die);

end

end

[p,q]=BDO(Inf,Inf)

a)


     Boo!

     p=NaN

     q=NaN

b)


     Boo!

     p=0

     q=0

c) Error

d) p=NaN

Answer: a

Explanation: Since the number of outputs sought are greater than 1, the if condition gets satisfied and ‘Boo !’ is printed. Inf-Inf will be NaN and hence both p and q will be equal to NaN.

12. What is the output of the following code?


function [die,af] = Bod(y,x)

die = y*x;

if nargout < 1

    error('Boo !')

 else

   disp(‘Yo !’)

   af = abs(die);

end

end

[p]=Bod(1,[1 -2])

a) Error with Boo! displayed

b)


     Yo !

     p=1

c)


     Yo !

     p=2

d)


     Yo !

     p=-2

Answer: d

Explanation: Only one output is sought from the Bod function. The first argument it returns is die=-2 and the else condition is also satisfied so Yo! will be printed.


13. What is the output of the following code?


function [die,af] = lola(y,x)

die = y*x;

if nargout < 1

    error('Boo !')

 else

   disp(‘Yo !’)

   af = abs(die);

end

end

p=lola(1,[1 -2])

a) Error with Boo ! written

b)


     Yo !

     p=-2

c)


     Boo !

     p=-1

d)


     Boo !

     p=1

Answer: a

Explanation: Since the number of argument sought are less than 1, nargout is less than 1 and the if condition is satisfied so the function terminates with an error.


14. A function ______________

a) can be run in the command window by defining it in the window itself

b) can be run in the command window by defining it in a cpp file

c) can be run in the command window by defining it in a script file

d) can be run in the script file by defining it in the command window

Answer: c

Explanation: A function has to be saved as a M-file before it can be run in the command window. We will have to take MATLAB to the directory where it is saved and it will run the function from the directory itself.

15. What is the output of the following code?


function c = addem(ap,q)

p=nargn-1

switch p

    case 2

        c = ap*q;

    case 1

        c = sin(q)

    otherwise

        c = 0;

end

addem(1,2,3,4,5,6,7,8)

a) 2

b) Error due to too many inputs

c) 28

d) Error due to nargn

Answer: d

Explanation: The first error MATLAB invokes is the fact that too many values are given as input. So it returns that as input. The next error would be that the nargin keyword is misspelled as nargn. But MATLAB returns the first error only.

This set of MATLAB Questions and Answers for Aptitude test focuses on “Commands for Parsing Input and Output – 2”.


1. The working of the varargin command is dependent on the nargin command implicitly.

a) True

b) False

Answer: b

Explanation: The varargin command takes the values as a cellular array. It takes values independent of the output of the nargin keyword.

2. The nargout command is dependent on the number of outputs sought.

a) True

b) False

Answer: a

Explanation: The nargout command acts according to the number of outputs sought from a function. It will change the output according to the value it gets assigned.

3. What is the output of the following command?


function eclairs= honey(p,q)

narginchk(2,5)

disp(‘Yo, G!’)

c=q+p;

end

honey(1)

a) Syntactical Error

b) Yo, G!

c) input error

d) 2 3 4 5

Answer: c

Explanation: The minimum number of inputs as suggested by the narginchk keyword is 2. But we have given only 1 input to the narginchk keyword. Hence, MATLAB gives an error in the input given to the function honey.

4. What is the output of the following command?


function p= marie(p,q)

narginchk[2,3]

disp(‘Yo, G!’)

a=p+q

end

marie(1)

a) Syntactical Error in narginchk

b)


    Yo, G!

     a=1

c) Input error in narginchk

d) 2 3 4 5…Inf

Answer: a

Explanation: There has been syntactical error while using the narginchk command in the marie function. The input to this keyword is given within a parenthesis. If the input was given within parentheses, the output would’ve been

Yo, G!

a=1

5. What is the output of the following command?


function ca= ola(p,q)

narginchk(0,1)

disp(‘Stick!’)

o=p-q;

end

ola(1,2)

a) o=-1

b) o=1

c) Error in inputs

d) Syntactical error while calling function

Answer: c

Explanation: The narginchk command has limited the number of inputs to the ola function to 1. But the ola function has been called and 2 inputs are given to it. This gives an error while getting an output from the function.

6. What is the output of the following command?


function pu= hu(p,varargin)

narginchk(0,1)

disp(‘Stick!’)

o=sin(varargin{1});

end

ola(1,p/2)

a) Error due to line 2

b) Error due to line 5

c) Error due to syntax

d)


     Stick!

     o=1

Answer: a

Explanation: The varargin command restricts the input to the function to only 1 argument. Hence, the function stops working and we will get an error due to line 2 of the above code.


7. The narginchk command can limit the size of which cellular array?

a) fun

b) rand

c) eye

d) varargin

Answer: d

Explanation: The varargin keyword is used to take inputs to function as a 1*N cellular array. The value of N can be limited by uing the narginchk command. The rand command generates 2 random numbers and the narginchk command has no effect on it. Same goes for the rest of the options since they are separate operations.

8. The nargoutchk command limits the length of which cellular array?

a) varargout

b) i

c) random

d) laplace

Answer: a

Explanation: The varargout command allows 1*N outputs to be asked from the function where it is situated. But the nargchkout command restricts the total number of outputs that can be sought from the function. So it really puts a limit to the value of N. Hence, the correct option is varargout.

9. The following operation results in?


narginchk(2,Inf)

a) Error due to Inf

b) Limits the length of nargin from 2 to Inf

c) Logical Error

d) Limits the length of varargin from 1 to Inf

Answer: d

Explanation: The narginchk keyword, if present in a function, limits the input to the same function within a range. According to the above operation, if we use the varargin array while takin’ input in a function, the function will return an error if the number of inputs to the function are less than 2.

10. The following operation result in


Function p= ol(q,varargin)

narginchk(45,Inf)

a) Error due to Inf

b) The range of the varargin array becomes 

c) The range of the varargin array becomes 

d) The range of the varargin array becomes [45,Inf]

Answer: b

Explanation: The narginchk keyword limits the size of the varargin array to atleast 44 or the function won’t run. This is because the first input to a function does not go in to the varargin array but to q and hence, the minimum number of elements the varargin array has to take is 44.

11. The following operation results in


Function p= ol(q,varargin)

narginchk(45,NaN)

end

a) Error due to NaN

b) Syntactical error

c) Logical Error

d) Nothing happens

Answer: d

Explanation: We have only written the code for the function but we did not call the function. So nothing will really happen although there is an error due to NaN. This doesn’t affect the saving of the function. It gets compiled at runtime.

12. What is the minimum number of arguments after the following operation occurs in any function?


narginchk(-2,0)

a) 0

b) 1

c) -2

d) Error

Answer: a

Explanation: The minimum number of arguments to be given to the function will become 0. This renders the function totally useless. One has to be careful while giving input to the narginchk command.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “User Input and Screen Output – 1”.


1. What is the output of the following code?


error(“Lola !”);

a) Output is suppressed

b) Syntactical error

c) No such function exists

d) It displays Lola !

Answer: b

Explanation: The input to the error command should be in ‘’ but here, “” was used which results in a syntactical error.

2. What is the output of the following code?


error(‘Dan !’);

a) No output, it gets suppressed

b) The word Dan ! is displayed

c) No such function

d) Syntactical Error

Answer: b

Explanation: The output won’t get suppressed due to the ; since this command is used to display the input given to it. There is no syntactical error.

Output: Dan !

3. What is the output of the following code?


error(‘ No !!!!’)

a) No !!!!

b) No !!!!

c) Logical Error

d) Symbolic error

Answer: b

Explanation: The input to the error command will be displayed in red. This is in contrast to the disp command and hence option No !!!! is correct.

Output: No !!!!

4. What is the output of the following code?


error(‘Lola ! \n Dan !’);

a) Output is suppressed

b) Symbolic error in \n

c)


    Lola ! 

    Dan !

d) Lola ! \n Dan !

Answer: d

Explanation: We can give multiple input to the error command. But the ‘\n’ character on;y works if we give multiple input like error where 1Arg, 2Arg are different variables which gets displayed due to the error command itself. If that’s the case, the output would have been option c. But here we have only 1 string argument and so the \n character won’t work.

Output: Lola ! \n Dan !

5. What is the output of the following code?


MException('Lola!', '%d * %d= Why?', Inf,Inf)

a) Error due to identifier

b) Error due to Inf

c)


    MException with properties:

    identifier: 'Lola!’

    message: 'Inf * Inf= Why?'

    cause: {}

    stack: [0×1 struct]

d) No such command

Answer: b

Explanation: The message identifier, ‘ Lola !’ given as an input to the MException command is not a valid MATLAB identifier. There is a set of valid identifiers and any input other input will give an error.

6. What is the output of the following code?


MException('MATLAB:test', '%d * %d= Why?', Inf,Inf)

a)


    MException with properties:

    identifier: ‘MATLAB:test’

    message: 'Inf * Inf= Why?'

    cause: {}

    stack: [0×1 struct]

b)


    MException with properties:

    identifier: “MATLAB:test”

    message: 'Inf * Inf= Why?'

    cause: []

    stack: [0×1 struct]

c)


    MException with properties:

    identifier: ''MATLAB:test’

    message: '%d * %d= Why?'

    cause: {}

    stack: [0×1 struct]

d) Error

Answer: a

Explanation: %d would get converted to the value given as an argument after the message input in the MException command. The cause is not specified so it would remain a cell array, identified by {}. The identifier is shown within a ‘’ and not “”.There is no error in the code.

Output:

    MException with properties:

    identifier: ‘MATLAB:test’

    message: 'Inf * Inf= Why?'

    cause: {}

    stack: [0×1 struct]

7. What is the output of the following code?


disp(‘%d’,Inf);

a) Inf

b) No such command

c) Error due to too many arguments

d) Syntactical error

Answer: c

Explanation: The disp command takes a maximum of 1 argument which is a string argument only. Hence it will return an error due to the second argument, Inf, given to it.

8. What is the output of the following code?


sprintf(‘%d’,5)

a) 5

b) ‘5’

c) Syntactical error

d) Logical error

Answer: b

Explanation: The sprint command will convert the argument variables given to it into the format specifier mentioned as an input. But, the new value output of the sprint command will be assigned to a variable, here it’ll be the ans variable, which will be a string variable.

9. What is the output of the following code?


warning(‘Pikapi !’)

a) Warning: ‘Pikapi !’

b) Warning: Pikapi !

c) Warning: ‘Pikapi !’

d) Warning: Pikapi !

Answer: d

Explanation: A warning message is always displayed in a dark yellow color. The message itself is not shown as contained within a ‘’. Hence, option Warning: Pikapi ! is correct.

Output: Warning: Pikapi !

10. What is the output of the following code?


warning('off')

warning('Pikapi !')

a) No output

b) Warning: Pikapi !

c)


    Warning: Off

    Warning: Pikapi !

d) Syntactical error

Answer: a

Explanation: No warning message will be displayed by MATLAB since we’ve disabled the working of the warning command itself with working. We can again enable it by simply writing warning.

11. What is the output of the following code?


disp(‘ ‘,lola!’ 2’)

a) ‘lola!’ 2

b) ‘ ‘lola!’ 2’

c) ‘lola! 2’

d) Error due to multiple arguments

Answer: d

Explanation: Within the ‘’, when we’re giving input to the disp command, the we cannot include another set of ‘’. This will given an error. The next set of ‘’ will be treated as an extra character argument while the first set of ‘’ will close itself once we give a ’ for our first set of single-inverted commas. This means, in the above command, after disp the input argument is already taken as a space character by the command while starting from lola.. the entire thing is another argument.

12. How many arguments are given to the above command?


disp(‘ ‘lola!’ 2’)

a) Cannot be defined

b) 2

c) 1

d) 0

Answer: c

Explanation: The syntax of the disp command is disp. To introduce further arguments, we habe to use disp. Now, once we end our string argument, we need to put a comma. Here, we haven’t put any comma so it shows that there is only 1 string argument while the rest is not defined as an argument also.

13. What is the output of the following command?


sscanf(‘.1 .2 .3’,%d)

a) []

b)


 

    .1

    .2

    .3

c)


 

    1

    2

    3

d) Error

Answer: a

Explanation: The input contains a string of floating point variables but the format specifier is for integer type.

14. The default exponential order for %e and %E is same.

a) True

b) False

Answer: a

Explanation: %e will signify the exponential order as e while %E will signify it as E. But the default order of representation of both of them is same.

Answer: b

Explanation: The disp command can print integers given as an input to the command. It is not necessary that the input has to be given as string argument.


Sanfoundry Global Education & Learning Series – MATLAB.

This set of MATLAB Assessment Questions and Answers focuses on “User Input and Screen Output – 2”.


1. What is the output of the following code?


sprint(‘%i’,91293)

a) 91293

b) Syntactical Error

c) The format specifier does not exist

d) ‘91293’

Answer: d

Explanation: The format specifier %i is used to display integers. But sprint keeps the input arguments in a character array. Hence, the output is ‘91293’.

Output: ‘91293’

2. What is the output of the following code?


sprintf(‘%E’,912)

a) 9.120000E+02

b) 9.120E+02

c) 9.1200E+02

d) 9.12000E+02

Answer: a

Explanation: If we don’t mention a precision amount, the default number of digits shown after the decimal place will be 6. Hence, option 9.120000E+02 is correct only. Option 9.120E+02 is true for %.3E used as the format specifier.

Output: 9.120000E+02

3. What is the output of the following code?


sprintf(‘%d %d %d’,.1, .2.3)

a) Error

b) ‘1.000000e-01 2.000000e-01 3.000000e-01’

c) 1.000000e-01 2.000000e-01 3.000000e-01

d) []

Answer: a

Explanation: The %d format specifier converts the arguments into those given in option ‘1.000000e-01 2.000000e-01 3.000000e-01’. But we have not given a, after .2. So, .3 is not even considered an argument and .2.3 together results in an error.

4. What is the output of the following code?


disp({12 })

a) [12]

b) 12

c) [12 ]

d) Error

Answer: a

Explanation: The input to the disp command is a cellular array. Cellular arrays are displayed within []. Output: [12]

5. What is the output of the following code?


size(‘’)

a) 0

b) Error

c) 0 0

d) 1 1

Answer: c

Explanation: The size command returns the nature of input given to the command. Here we have given an empty string as an input but the size of the string will return the number of rows and columns present in the input string which is 0 and 0. The ‘’ indicates a 2-D character array which has 0 rows and 0 columns; 0 is treated as a value while returning the size of the input.

6. What is the output of the following code?


sprintf('%04.2f',2.9121)

a) ‘2.91210000000000000000’

b) ‘2.91’

c) 2.91

d) Error

Answer: b

Explanation: %4.2f implies that the input argument, 2.9121, will be approximated to 4 places places before the decimal point and 2 places after it.

7. What is the output of the following code?


sprintf(); disp();

a) Error due to disp

b) Error due to sprintf

c) Both gives an error

d) No output is displayed

Answer: b

Explanation: Both would give an error due to absence of any input arguments in the commands. But sprintf will give an error first as MATLAB returns the first error it finds.

8. What is the output of the following code?


P=disp(234)

a) Error

b) P=234

c) 234

d)


     P=

        234

Answer: a

Explanation: No output arguments can be initialized by the disp command. It would have displayed 234 only if the command was disp but here there will be error because we are assigning the output of the disp command to a variable. This is possible by the sprintf command.


9. How can we influence the disp command with format specifiers?

a) Not possible

b) Via the sprintf command

c) Use format specifiers as string input

d) Give format specifiers as input only

Answer: d

Explanation: We can create a character array using the sprintf command and we can use format specifiers in the sprintf command. So, the final character array can be printed by giving that variable as an input to the disp command.

10. What is the output of the following code?


disp(“12”)

a) ‘12’

b) “12”

c) 12

d) Error

Answer: c

Explanation: The string argument, given as an input to the disp command, can be given within “” and hence, the output is 12 only. There rest of the options are incorrect.

11. What is the output of the following code?


fprintf(“%f”,.123)

a) .123000

b) %f

c) Error

d) .123

Answer: a

Explanation: Since we haven’t mentioned a precision while representing .123, the output will be upto 6 places of decimal. Thus, the output is .123000 and there is no error.

12. What is the size of ans variable after the following code?


sprintf('23 23')

ans=

      ’23 23’

a) 14 bytes

b) 10 bytes

c) Error

d) 1*5

Answer: b

Explanation: The number of elements in the character array, given as input are 5. They are ‘2’, ‘3’, ‘ ’, ‘2’, ‘3’. Hence, the total size will be 10 bytes as each element will take 2 bytes. The ‘’ are not taken as elements.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Evaluation – 1”.


1. What is the output of the following code?


[q]=eval(sprintf('23 '))

a) q=23

b) Logical Error

c) Symbolic error

d) No output

Answer: a

Explanation: As eval evaluates the MATLAB expression in the input, it will evaluate the input to 23 and assign it to q. There are no errors in the above code.

2. What is the output of the following code?


[q,r]=eval(‘sprintf('23 45')’)

a) Unexpected MATLAB expression

b) q=23,r=45

c)


   q = 23

   r = 45

d) Error due to eval

Answer: a

Explanation: The eval command returns an error if more than a pair of inverted commas are found. Hence, unexpected MATLAB expression is correct option. Option q=23,r=45 cannot happen since 23 and 45 will be stored in a single character array.

3. What is the output of the following code?


p=eval(cos(0));

a) p=1

b)


    p=

      1

c) Syntactical error

d) The eval command does not exist

Answer: c

Explanation: An input to the eval command will have to be within a pair of inverted commas. Here, we haven’t used them so MATLAB will return an error.

4. What is the output of the following code?


evalc(‘cos(0)’)

a) No such command

b) Error

c) 1

d) ‘ ans=1 ’

Answer: d

Explanation: Evalc takes the entire output of the input expression into a string. Hence, it will show a as an answer were the entire thing will be shown, within, as a string.

5. What is the size of p from the following code?


P=evalc(‘ ’)

a) 2 bytes

b) 0 bytes

c) Error

d) 6 bytes

Answer: a

Explanation: The evalc command results in an empty character array. Hence, the size of p will be 0 but it’s class will be char.

6. The for keyword can be used to evaluate expressions using eval.

a) True

b) False

Answer: b

Explanation: Reserved keywords cannot be used explicitly in the eval command. But they can be used by mentioning a function which is defined to use a for loop.

7. The evalc function is different from the eval command ________

a) no difference

b) from precision of output

c) from nature of output

d) from display of output

Answer: d

Explanation: The entire output is displayed as a character array using evalc while the eval command displays the output itself. There is no difference in precision or nature of output.

8. What is common to evalc and the eval commands, apart from the output?

a) The error message is displayed separately

b) The outputs are of different accuracy

c) There is nothing common

d) evalc does not exist

Answer: a

Explanation: The error messages, if any error, pertaining to the input expression, occurs, are displayed separately by both the command.

9. What is the output of the following code?


P=eval(‘ ’)

a) P= ‘ ’

b) P will be an empty character array

c) Error

d) No such function

Answer: c

Explanation: We have assigned the output of the eval command to an expression. Hence, we will have to give an expression within ‘’ which results into any value. Here, we haven’t provided any expression so the statement in not complete. Hence, MATLAB returns an error.

10. What is the output of the following code?


feval(“sum”,1234,1)

a) Syntactical error

b) Logical Error

c) 1235

d) ‘1234’

Answer: c

Explanation: There is no error in the following code. The string input to the feval command can also be given within ‘’. Hence, the final output is 1235.

Output: 1235

This set of Basic MATLAB Questions and Answers focuses on “Evaluation – 2”.


1. What is the output of the following code?


feval[‘round’,123.12]

a) 123

b) 123.12

c) 123.1

d) Error

Answer: d

Explanation: The input arguments to the feval command cannot be given within [], it should be included within parentheses. Hence, an error will be returned. If the input was within parentheses, the output would’ve been 123 only.

2. The feval command can evaluate __________

a) A single command

b) Multiple commands

c) Multiple functions

d) No such function exists

Answer: a

Explanation: The input string argument to the feval command should contain only 1 command. If we give multiple commands to be evaluated, it will give an error.

3. The eval command can evaluate __________

a) A single function

b) Only a single command

c) The function does not exist

d) Multiple commands

Answer: d

Explanation: The eval command can evaluate multiple commands at the same time and show their answer but it cannot assign to variables.

4. The input to the eval command is given using [].

a) True

b) False

Answer: b

Explanation: The input argument to the feval command is given within parentheses. Hence, MATLAB will return an error if we use [].

5. The input to the evalc command is given using {}.

a) True

b) False

Answer: b

Explanation: The input argument to the evalc command is given within parentheses. Hence, MATLAB will return an error if we use {}.

6. What is the value of ans from the following code?


feval(‘sin(0),cos(0),123’)

a) 123

b) 0,1,123

c) Error

d) 0

Answer: a

Explanation: The value of ans will keep changing after every expression gets evaluated in the string argument. So the final expression is 123 which will be the last value assigned to the ans variable.

Output: 123

7. What is the output of the following code?


evalc(‘Laplace(t)’)

a) Syntactical Error

b) Symbolic error

c) ‘1/s 2 ‘

d) 1/s 2

Answer: b

Explanation: There is an error in the following code. It would’ve simply evaluated the laplace transform of t which is 1/s 2 but t is not defined as symbolic. Hence, MATLAB will return an error.

8. Which function gets disabled while using evalc?

a) diary

b) sin

c) inf

d) round

Answer: a

Explanation: The diary command gets disabled when we try to use the evalc command in MATLAB. The commands sin and round work just fine while Inf is not a function.

9. How much does the precision change while finding sin using evalc and eval?

a) 10%

b) 2%

c) 20%

d) No change

Answer: d

Explanation: The purpose of both the commands is simply to make the commands, provided in the input argument, work. They do not hamper the precision with which the commands evaluate a value.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Debugging”.


1. Can we save a MATLAB program while in debugging mode?

a) True

b) False

Answer: b

Explanation: While in debugging mode, we are really trying out the function. So, when the debugging mode starts, the command line is halted at a certain line in the function and the evaluation of the function is stopped. Hence, it’s not possible to bring a change in the function and save it in the directory. We’ve to exit from the debugging mode and then we can save the function.

2. To enter a value and change the course of working of a function while it is working, we use the __________

a) dbstop

b) db

c) keyboard

d) enter

Answer: c

Explanation: The keyboard command is pre-defined in MATLAB and allows us to enter the debugging mode. We need to give the command in our m.file where we want to start debugging and then the control will return to the keyboard where we will be able to give new value to the parameters involved in the function.

3. To end the debugging mode, we use the __________

a) dbquit

b) dbend

c) debugend

d) No such function

Answer: a

Explanation: The dbquit command can be used to exit from the debugging mode. This is pre-defined in MATLAB. dbend and debugend commands don’t exist.

4. Which of the following command would allow us to continue the evaluation of a function in the debugging mode?

a) dbcont

b) dbcontinue

c) continue

d) debugcont

Answer: a

Explanation: The dbcont command would allow us to continue the working of our function after we have entered the debugging mode. The continue command is used in loops, it won’t help us in this case.

5. What is dbstop command?

a) exits from the debugging mode

b) pauses for the debugging mode when a condition is reached only

c) exits the debugging mode at any point in the function

d) does not exist

Answer: b

Explanation: The dbstop command stops the debugging mode. Now, we can give the dbstop command in many ways. One of the ways is mentioning a condition, regarding when the working of the function should stop, to enter the debugging mode. To exit from the debugging mode, we need to use the dbquit command.

6. The dbstop command, for anonymous functions __________

a) Pauses, for debugging, after the line which dbstop indicates

b) Pauses, for debugging, before the line which dbstop indicates

c) exits from the debugging mode after the line which dbstop indicates

d) exits from the debugging mode before the line which dbstop indicates

Answer: a

Explanation: For anonymous functions, the dbstop command works differently in contrast to pre-defined functions. This nature of working is only for anonymous functions which are not stored in the MATLAB memory. The dbquit command is used to exit from the debugging mode.

7. The dbquit command, if placed in an m.file, will __________

a) never run the debugging mode

b) exit from the debugging mode

c) result in an error while running the function

d) dbquit does not exist

Answer: c

Explanation: This command will result in an error if it is placed within an m.file. This is because debugging commands can only be used when the control enters debug mode and we need to give these commands only from the command window.

8. The dbcont command, if placed in an m.file, will __________

a) not allow the function to be saved

b) give error when we enter dbcont in debug mode

c) will give an error during function call

d) dbcont does not exist

Answer: b

Explanation: The function will be saved and it will run. After enter the debugging mode, and making any desirable change, when we enter the dbcont command, the function will keep working until it invokes the dbcont command. Then it will result in an error and the control will break the evaluation of the function entirely.

9. The dbstop command, for functions stored in the system memory, with a line mentioned will __________

a) pause the evaluation of the function before the mentioned line

b) exit the evaluation of the function before the mentioned line

c) pause the evaluation of the function during the mentioned line

d) pause the evaluation of the function after the mentioned line

Answer: a

Explanation: In contrast to anonymous functions, the dbstop command will pause the working of a function just before the mentioned line. It will pause the evaluation and enter the debugging mode.

10. The debug commands can be run in

a) functions

b) live scripts

c) command window

d) nowhere

Answer: c

Explanation: The debug commands can only be run from the command window. If they are present in user-defined functions or live scripts, the working of the function would entirely stop when any debug command is invoked while evaluation of the function.

11. What are the contents of a after the following events?


function p=avg(x)

n = length(x);

Command Window: 

>> x=[1 2 3 4 5]

>> dbstop in avg at 2 if length(x)>4

>> a=avg(x)

a) Enters debugging mode

b) Error in the command window

c) Error in the function

d) 5

Answer: a

Explanation: This is a simple code. The kernel will enter the debugging mode since the condition given by dbstop is not satisfied. The length of the x vector is 5 in the command window which results in the kernel to shift to the debugging mode.

12. What are the contents of a after the following events?


function p=avg(x)

n = length(x);

Command Window: 

>> x=[1 2 3 4 5]

>> dbstop at 6 if length(x)>4

>> a=avg(x)

a) Error in 2 nd line of command window due to line no

b) Error in 2 nd line of command window due to line missing function name

c) 5

d) Enters the debugging mode

Answer: b

Explanation: The first error encountered by the debug command is that the function name is missing i.e the function name must be given to the dbstop command. The second error is the fact that the function, defined already, has only 2 lines but we have asked the kernel to enter the debugging mode at line 5. Since MATLAB returns the first error it faces.

13. What are the contents of a after the following events?


Line 1: function p=avg(x)

Line 2: n = length(x);

Line 3: n=n+3

Command Window: 

>> x=[1 2 3 4 5]

>> dbstop in avg if length(x)>4

>> a=avg(x)

a) 8

b) Enters debugging mode after execution of the last line

c) Enters debugging mode at the first line only

d) Enters debugging mode at the 2 nd line

Answer: c

Explanation: We haven’t mentioned the line no. where the debugging mode should begin if the condition provided with the dbstop command is unsatisfied. Hence, debugging will start at the first line only.

14. What are the contents of a and b after the following events?


Line 1: function p=avg(x)

Line 2: n = length(x);

Line 3: n=n+3

Command Window: 

>> x=[1 2 3 5]

>> dbstop in avg if length(x)>4

>> a=avg(x);

>> x=[1 2 3 4 5];

>> b=avg(x);

a) Error in the function

b) a=4,b=5

c) Enters debugging mode at b but a=4

d) Outputs are suppressed

Answer: b

Explanation: The dbstop command would work if the function is called after we have given the dbstop command. It won’t affect the working of the function if the function is called any more number of times i.e the condition provided in the dbstop command won’t result in entering the debugging mode if the working of the function does not satify it.

15. The return command is similar to the dbcont command.

a) True

b) False

Answer: a

Explanation: The working of the return command is similar to the dbcont command. It will get from the debugging mode and return to evaluate the function completely.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Modeling – 1”.


1. What has been modelled in the following Simulink screenshot?

matlab-questions-answers-modeling-1-q1

a) The step response of the unit step signal with a step time=0

b) The step response of the ramp signal with a step time=4

c) The ramp response of the step signal with a ramp slope=1

d) The step response of the unit step signal with a step time=2

Answer: a

Explanation: Since the step function is given as an input to the system whose transfer function is s, the above screenshot shows the modelling of a system whose impulse response is a step function while the input is also a step function. The graph suggests that step time is 0.

2. The system, that has been modelled in the following Simulink screenshot has ___ initial conditions.

matlab-questions-answers-modeling-1-q2

a) 0

b) Some

c) Impossible

d) Cannot be determined

Answer: b

Explanation: We note that the ramp function does not start from 0 at t=0. This implies that it has some initial conditions.

3. Digital systems ______ in Simulink.

a) Can be implemented

b) Cannot be implemented

c) Only ADC’s

d) Only DAC’s

Answer: a

Explanation: Logic systems and bitwise operator section under Simulink provides the user with a multitude of operators for digital system. MATLAB also has HDL doe verifier.

4. The no. of logical operations present in the logical operator block is _________

a) 6

b) 7

c) 5

d) 3

Answer: b

Explanation: The logical operations present are AND, NOT, OR, NAND, NOR, XOR and XNOR. Hence, the correct option is 7.

5. The arrows connecting each block with another are ____

a) Flexible as in they don’t become permanent when once placed

b) Rigid as in their direction cannot be changed

c) Don’t pop up in the screen

d) Absent

Answer: a

Explanation: By clicking the head of the arrow, we can drag it and change it’s direction. Also we change the alignment of the body by keeping the cursor pressed on the arrow body, while moving that part of the body. It does show on the screen, i.e. it’s head and it’s tail.

6. The output at scope 1 is?

matlab-questions-answers-modeling-1-q6

a) 0

b) Impulse function

c) Ramp function

d) Step function

Answer: a

Explanation: The derivative of the step function is 0. This is because the step function has a constant amplitude.

7. What have we modelled here?

matlab-questions-answers-modeling-1-q6

a) A capacitor which is blocking DC

b) An inductor which is blocking AC

c) A resistor whose resistance changes with temperature

d) A capacitor which is being charged

Answer: a

Explanation: The output of the derivative block will be 0. Hence this system shows a model of the event described in capacitor which is blocking DC. Note that to model option inductor which is blocking AC, we need an integrator which takes a high frequency sinusoid.

8. What can be the possible limitation of this block?

matlab-questions-answers-modeling-1-q8

a) No. of zeros never equal to no. of poles not allowed

b) No. of zeros lesser than no. of poles not allowed

c) No. of zeros greater than no. of poles not allowed

d) No. of zeros equal to no. of poles not allowed

Answer: c

Explanation: The system having more zeros than poles is extremely unstable and not realizable. Hence, this is the only possible limitation of the given block.

9. The limits of the graph obtained from the scope can be changed from the ________

a) Configuration properties

b) Style option

c) Layout option

d) Stepping option

Answer: a

Explanation: In the window, which contains the graph obtained from the scope block- there is the option of Configuration Properties in the View option. We can modify the limits of both axis from that segment. The layout and style options don’t contain the axes.

10. For this block, the early voltage is always infinite.

matlab-questions-answers-modeling-1-q10

a) Yes

b) No

c) Not always

d) Cannot be determined

Answer: c

Explanation: The Early voltage can be specified amongst the parameters of the NPN B.J.T. It can also be put to Infinite for the sake of calculations- though it never happens in reality.

This set of MATLAB Problems focuses on “Modeling – 2”.


1. We _______ simulate circuits in MATLAB.

a) can

b) cannot

c) can, only by blocks

d) can or cannot

Answer: a

Explanation: Not only by blocks, but electronic components are also present in the Simscape toolbox. We can simulate the working of circuits via this toolbox. We would need a source and the scope to generate and view waveforms of input and output respectively.

2. Photodiodes are present in the _________ section of the Simscape toolbox

a) Special Purpose Diodes

b) Semiconductor devices

c) Diodes

d) Sensors

Answer: d

Explanation: It is not present in the section mentioned in semiconductor devices, diodes and special purpose diodes, don’t exist as separate sections. It is really present in the sensors section since it acts like a sensor only.

3. Where is the following block present?

matlab-problems-q3

a) Nowhere

b) Sink

c) Source

d) Ground

Answer: c

Explanation: This block acts as a source and hence it’s placed in the Source section. This is different from ground.

4. The output in the scope is an analog signal.

a) True

b) False

Answer: a

Explanation: The output of the scope always shows as an analog signal. It is recommended to use other means of realizing digital outputs such as bulbs.

5. The Battery is also viewed as a charge dependent source.

matlab-problems-q5

a) True

b) False

Answer: a

Explanation: The battery can be modelled with an internal resistance and an internal capacitance. Hence, the above statement is true.

6. We can model __ impulse function in discrete domain

a) No

b) Unit

c) Shifted unit

d) Any

Answer: d

Explanation: The impulse function can be modelled by choice and it doesn’t matter how much we want to delay the impulse function nor the fact that it’s continuous or discrete.

7. What does the following model portray?

matlab-problems-q7

a) Measuring impulse response of a system

b) Measuring impulse response of a system

c) Measuring ramp response of a system

d) Measuring step response of a system

Answer: b

Explanation: We are giving a discrete impulse signal to the system represented by the transfer function which is that of a ramp function.

Output: matlab-problems-q7a

8. What does the following model show?

matlab-problems-q8

a) The discrete impulse is shifted by 8 units in time

b) The discrete transfer function is shifted by 8 units in time

c) The output has an error

d) The output does not match the graph

Answer: a

Explanation: The transfer function represents a ramp function. Now, the scope shows a graph starts from t=8 units in time and goes to 1 at t=9. Thus the impulse input given to the graph is actually shifted by 8 units in time.

9. What does this block do?

matlab-problems-q9

a) Gives a logic 1 if the input is greater than it’s previous value

b) Gives a logic 0 if the input is greater than it’s previous value

c) Gives a logic 1 if the input is smaller than it’s previous value

d) Gives a logic 0 if the output is greater than it’s previous value

Answer: a

Explanation: The above block gives a 1 if the input is strictly greater than it’s previous value. It returns a 0 if the input is less than or equal to it’s previous value, as defined in SIMULINK TOOLBOX.

10. What does this model do?

matlab-problems-q10

a) Generate a step and ramp function

b) Generate a ramp and parabolic function

c) Generate pulse function

d) Error

Answer: a

Explanation: A second order integrator block contains two output ports. The upper one integrates the input once, while the below one integrates the input twice. If we keep on integrating the impulse function, the output of the upper block will be a step function and that of the below one will be a ramp function.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Simulation – 1”.


1. What is the output of the following code?


simlink;

a) Error

b) Opens a window for Simulink

c) Closes MATLAB

d) Opens simlink and closes MATLAB

Answer: a

Explanation: There’s an error in the above code. It’s a typical spelling error which is why MATLAB doesn’t recognize the command. A ‘u’ is missing since the actual command is Simulink.

2. What does the following block do?

matlab-questions-answers-simulation-1-q2

a) Converts a Simulink signal to a physical Signal

b) Converts a Simulink variable to a physical variable

c) Converts a Simulink operation to a physical operation

d) Does nothing

Answer: a

Explanation: The above shown block does the work which converts a simulink signal to a physical signal. This is used to convert a signal from a transfer function toolbox, say, to a physical real signal which can be used for evaluation in circuits.

3. What does the following block do?

matlab-questions-answers-simulation-1-q3

a) It evaluates circuit parameters after steady state

b) It evaluates circuit parameters of every component during Simulation

c) It evaluates the equation f=0 for Simulink Signal

d) It does nothing

Answer: b

Explanation: It is connected to all separate n/w’s present in the model. It will calculate the parameters of every component present in the circuit, during Simulation, and the model won’t be simulated without this solver.

4. What is the error in the following model?

matlab-questions-answers-simulation-1-q4

The error in the above model is the absence of a ___ ground

a) Simulink

b) HDL coder

c) Simscape

d) A.C.

Answer: b

Explanation: The ground in Simulink toolbox is not compatible with circuits while the ground in the HDL Coder Toolbox is. The Simscape toolbox doesn’t have a ground. The HDL Coder ground is missing.

5. Is this block necessary for circuit analysis in the SIMULINK model?

matlab-questions-answers-simulation-1-q5

a) Yes

b) No

c) Only for AC analysis

d) Only for DC analysis

Answer: a

Explanation: This block is essential for analysis using circuits. Without it, the simulation won’t start in the Simulink model.

6. How can we connect the following blocks?

matlab-questions-answers-simulation-1-q6

a) By a wire

b) By converting the signal from the sensor to a Simulink Signal

c) By a VCCS

d) By a ground

Answer: b

Explanation: The signal from the current sensor is treated as a physical sensor to account for the noise, temperature changes in the environment of the circuit. Now, since this is a physical signal- we actually need to convert it to a signal which is compatible with the Simulink environment and this is done by a converter which converts a physical signal to a Simulink signal. Henceforth, we can connect the output of the converter to our scope and watch the output swing.

7. What does this block do?

matlab-questions-answers-simulation-1-q7

a) Sends a signal from one part of a circuit to another

b) Sends a signal from one file to another file

c) Sends a signal from source to destination

d) Sends a function from one signal to another

Answer: a

Explanation: This block is used to carry a signal from one part of the circuit to another. To exemplify the concept, we may want to see the graphs for the input and output voltage as a stack in the scope. We can connect the input to the scope via the Goto block instead of connecting the input signal through a wire with the scope.

8. What type of signals does this block take?

matlab-questions-answers-simulation-1-q8

a) Only real signals

b) Only Complex signals

c) Only digital signals

d) Any signal

Answer: d

Explanation: This block has essentially been designed in MATLAB to multiplex any kind of signal. It accepts both real and complex signals so it also takes digital signals.

9. When does the ramp function start in the following block?

matlab-questions-answers-simulation-1-q9

a) At t=0

b) User specified time

c) At t=1

d) Just after t=0

Answer: b

Explanation: The ramp function can start from any instant of time. This can be specified by the user while setting the parameters of the block.

10. Which waveform is not produced by the above block?

matlab-questions-answers-simulation-1-q10

a) Cosine

b) Tangent

c) Square

d) Sawtooth

Answer: b

Explanation: The cosine waveform can be generated by delaying the sinusoidal signal by pi/2. The Square and Sawtooth waveforms are also generated by this block. The signal to represent tan is not available in this block.

11. Which of the following takes a mathematical user-defined function directly?

matlab-questions-answers-simulation-1-q11

a) Left upper corner block

b) Right upper corner block

c) Left bottom corner block

d) Right bottom corner block

Answer: a

Explanation: The Fcn block allows a user defined function to operate on signals during simulation and directly give a desired mathematical function. The Interpreted MATLAB function block is used to call the MATLAB commands which are pre-defined in MATLAB. The Function Caller block is used to specify a stateflow chart which can be used as a separate function block.

12. What does this block do?

matlab-questions-answers-simulation-1-q12

a) Checks whether the input signal is non-zero

b) Check whether the output signal is non-zero

c) Checks whether a signal is zero

d) Checks whether we have a ground in the circuit

Answer: c

Explanation: The given block checks whether the input given to this block is 0 or not. If it’s 0, the block returns an error.

13. Is the battery voltage dependent on charge?

matlab-questions-answers-simulation-1-q13

a) Yes

b) No

c) It can be modelled

d) It cannot be modelled

Answer: c

Explanation: We can set the charge content of the battery and thereby make the voltage coming from it as a charge dependent voltage source which is quite nice for real time simulation.

14. Can we simulate transient states in Simulink.

a) True

b) False

Answer: a

Explanation: We can simulate the characteristics of a circuit in MATLAB. This means we can calculate the total response of a system in SIMULINK.

15. Does this block take noise into account?

matlab-questions-answers-simulation-1-q15

a) Yes

b) No

c) Sometimes

d) Only at high frequencies

Answer: b

Explanation: This block is treated as an ideal constant voltage source. It can be used in place of the voltage source already present in Simulink toolbox.

This set of Tricky MATLAB Questions and Answers focuses on “Simulation – 2”.


1. What does the following toolbox do?


Simulink Control Design

a) Plots bode plots

b) Verifies circuit modelling

c) Calculates z transform

d) Calculates Fourier transform

Answer: a

Explanation: The above toolbox is used for the analysis of the system and check the control system parameters which gives an insight into the nature of working and stability of the system that has been modelled.

2. What does the following block show?

tricky-matlab-questions-answers-q2

a) The maximum value of a signal

b) The minimum value of a signal

c) The final value of a signal

d) The rms of a signal

Answer: a

Explanation: The above block is configured to view the final value of a signal after simulation. It helps to identify the final value but only up to the time for which the model is getting simulated.

3. What does the following block do?

tricky-matlab-questions-answers-q3

a) Add a AC value to the input

b) Add a DC value to the signal

c) Add a noise to the signal

d) Add a white noise to the signal

Answer: b

Explanation: The Bias block is used to add a bias signal to any signal. This essentially means adding a DC value to the input i.e. if the input signal is a sinusoid, it’ll start from the given Bias or D.C. value at t=0.

4. What does the following block do?

tricky-matlab-questions-answers-q4

a) Add a delay to the signal in frequency domain

b) Advance the signal in frequency domain

c) Shifts the signal in frequency domain

d) Gives an output as the function of the input

Answer: d

Explanation: The above mathfunction takes an input and ends up giving an output according to the given input and the user-chosen function. It does not multiply the input with function so it really isn’t doing anything mentioned in the rest of the options.

5. What is the name of the given block?

tricky-matlab-questions-answers-q5

a) z-domain

b) Laplacian domain

c) Fourier domain

d) no domain

Answer: b

Explanation: The s domain is referred to the Laplacian domain. The z-domain has a separate block. Hence, only laplacian domain is correct.

6. Simulink allows the simulation of systems using block diagrams.

a) True

b) False

Answer: a

Explanation: The Simulink allows the user to set up blocks which represent functions and can be used to model a system. Hence, the above statement is true.

7. What is the function of the following block?

tricky-matlab-questions-answers-q7

a) Gives a 1 if the input is negative

b) Gives a 0 if input is negative

c) Gives a 1 if input is positive

d) Gives a 0 if input is positive

Answer: c

Explanation: The above block gives a 1 if the input is positive and a -1 if the input is negative.

8. What are the transistors present in Simulink?

a) BC-547

b) IN3914

c) No transistor

d) User defined

Answer: d

Explanation: The datasheet of any transistor can be specified in the transistor model. Hence, only option User defined is correct.

9. How many sinusoids can this block generate simultaneously?

tricky-matlab-questions-answers-q9

a) Only 1

b) Multiple

c) Only 1 at high frequency

d) Multiple with multiple frequency

Answer: d

Explanation: This block samples a sinusoidal signal and can generate multiple sinusoidal signals by giving vector inputs as parameters to the block.

10. What is the value of the constant supplied by the block?

tricky-matlab-questions-answers-q10

a) 1

b) 0

c) User defined

d) Not available in MATLAB

Answer: c

Explanation: This is a block present in MATLAB and can be used to model a constant signal. The value of the constant is user defined.

11. What is the no. of bits used for the counter operation by the following block?

tricky-matlab-questions-answers-q11

a) 3

b) 5

c) System defined

d) Minimum required

Answer: d

Explanation: This block uses the minimum no. of bits required for a counter operation. It doesn’t initialize bits according to the number of bits of the system so it saves a bit of memory.

12. What is the reference power while converting to dB for the following block?

tricky-matlab-questions-answers-q12

a) 1W

b) 1mW

c) 0

d) 20W

Answer: a

Explanation: The reference power for this block is pre-defined in MATLAB. To convert the voltage to dB, the reference power is 1W but to convert it to dBm, the reference power is 1mW.

13. This block can be used in what kind of systems?

tricky-matlab-questions-answers-q13

a) Logical

b) Continuous

c) Discrete

d) Any

Answer: d

Explanation: This block is not restricted to logical systems. It can be used for any system, which is being modelled in MATLAB, and check the simulation results at instants where the user feels it needs to be checked.

14. What does this suggest?

tricky-matlab-questions-answers-q14

a) The slope of the ramp function is 0

b) The slope of the ramp function is -1

c) The slope of the ramp function is 1

d) The value of the step function is 0

Answer: a

Explanation: Since the ramp function is plotted in the y-axis, it is seen that the value of the y axis is 0.

15. What is the function of this block?

tricky-matlab-questions-answers-q15

a) Defining only continuous systems

b) Defining only discrete systems

c) Defining only digital systems

d) Defining both continuous and discrete systems

Answer: d

Explanation: This block allows us to model both continuous and discrete time systems for simulation.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Calling External Functions”.


1. What is the function of the mexext command?

a) Reveals the version of the MEX file

b) Reveals the package in which the MEX file is stored

c) Returns the extension of the MEX file for the system

d) Error

Answer: c

Explanation: The MEX file, generated in MATLAB will have an extension which depends on system configurations. Hence, the above code returns the extension of the MEX file when generated from the current system.

2. What is the output of the following code?


Mexext(‘all’)

a) Error

b) Returns a structure of arrays of MEX extensions

c) Returns an array of structures of MEX extensions

d) Returns the system version of MEX file

Answer: a

Explanation: The mexext file is misspelled with the ‘M’, it should’ve been small. The MEX extensions would’ve been shown if the command was written properly.

3. What is the output of the following code snippet?


computer

a) Shows the system version

b) Shows the MATLAB version

c) Shows the previous MATLAB versions in the current system

d) Error

Answer: a

Explanation: It shows the version of the system where MATLAB is installed currently.

4. What is the output of the following code?


loadlibrary()

a) Load a C library

b) Load a C function

c) Load a C header file

d) Load a C file

Answer: a

Explanation: The above command typically loads a C library with all the header files and the functions so that they can be used in the MATLAB code.

5. The callib command implements the function from a _________

a) library loaded by the loadlibrary command

b) .h file loaded by the loadlibrary command

c) c-file loaded by the loadlibrary command

d) function loaded by the loadlibrary command

Answer: a

Explanation: The callib command is defined in MATLAB to use a function which is in a pre-loaded C library. The function can be called by giving the function name and the arguments as an input to the callib command.

6. What is the working of the following command?


libfunctions()

a) Returns the pre-loaded libraries

b) Returns the libraries in a pre-loaded library

c) Returns the header-files in a pre-loaded C library

d) Returns the functions in a pre-loaded library

Answer: d

Explanation: The above command returns the functions, in a library- the library name is given as an input to the command. The library is to be pre-loaded with the loadlibrary command.

7. What is the working of the following command?


libfunctions(libname,'-full')

a) Returns the functions of a shared library

b) Returns the functions of a shared library and it’s signatures

c) Returns the signatures of the functions of a shared library

d) Error

Answer: b

Explanation: The above command returns both the set of functions present in the shared C library and the signature of each function in the pre-loaded library.

8. What is the working of the following command?


libfunctionsview

a) Displays the signatures of the function in an image window

b) Displays the signature of the functions in a graphical window

c) Displays the signature of the functions in the workspace window

d) Displays the signature of the function in a separate window

Answer: d

Explanation: The above command returns the signatures of the functions present in a library. The library name is given as an input to the command.

9. The libfunctionsview command shows the signature of the functions present in the ___________

a) pre-loaded library

b) any library

c) Java library

d) Not present

Answer: a

Explanation: The libfunctionsview command works only on a library that has been pre-loaded into MATLAB with the loadlbrary command.

10. What is the working of the following command?


libisloaded()

a) Checks the version of the loaded library

b) Checks whether a library is working in the system

c) Checks whether a library is loaded in the system

d) Checks whether a library is present in the system

Answer: c

Explanation: The above command returns a 1 if it finds that the library, given as an input to the command, is pre-loaded in the system.

11. Which of the following command unloads a library from the system?

a) unldlibrary

b) unloadlibrary

c) unloadlibrary{}

d) unldlibrary[]

Answer: b

Explanation: The correct command to unload a library is unloadlibrary. It is syntactically correct and no misspelling.

12. The isjava command returns?

a) 1 if the input is a java file

b) 1 if the input is not a java object

c) 1 if the input is a java object

d) 0 if the input is a java object

Answer: c

Explanation: The isjava command will return a 1 if the input to the command is a java object. It would return a 0 otherwise.

13. The input to the isjava command is given within _________

a) 

b) []

c) {}

d) Doesn’t exist

Answer: a

Explanation: The input to the isjava command should be given within parentheses. It would return an error otherwise.

14. The isobject returns a 1 if the _________

a) A is a MATLAB class

b) A is a JAVA class

c) A is a C file

d) A is not a MATLAB class

Answer: a

Explanation: The above command checks if the input given to it belongs to the MATLAB class. If it’s so, it’ll return a 1- else it’ll return a 0.

15. Python files cannot be used in MATLAB.

a) True

b) False

Answer: b

Explanation: Python files can be used in MATLAB. Python commands cannot run in MATLAB without Python in the system.

16. Python commands can be run in MATLAB without Python in the system.

a) True

b) False

Answer: b

Explanation: A version of C python is required to be present in the system for python commands to run. Hence, the above statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Toolbox Distribution – 1”.


1. What is the extension of a newly created toolbox?

a) .mltbx

b) .mlx

c) .tlx

d) .tbx

Answer: a

Explanation: A MATLAB Toolbox has the extension .mltbx. This is created when we produce a toolbox which is defined by the user.

2. What does the following function do?


matlab.addons.toolbox.packageToolbox

a) Converts a .prj file to a .mltbx file

b) Converts a .mat file to a .mltbx file

c) Converts a .mltbx file to a .prj file

d) Converts a .mltbx file to a .prj file

Answer: a

Explanation: The above function is defined in MATLAB to convert a user-defined toolbox into a installation file which can be used by other people to use your toolbox. The extension of this installation file is .mltbx.

3. What does the following function do?


matlab.addons.toolbox.toolboxVersion

a) Shows all versions of a toolbox

b) Shows the current version of a toolbox

c) Shows the previous versions of a toolbox

d) Error

Answer: b

Explanation: The above function is used to get the version of the toolbox which will be given as an input to the above function. It doesn’t show the previously installed versions or the versions which are possibly present.

4. The input to the function “matlab.addons.toolbox.toolboxVersion” is given within ______

a) Parentheses

b) {}

c) []

d) The function doesn’t exist

Answer: a

Explanation: The input to this function is given within parentheses. This is pre-defined in MATLAB and hence, only option Parentheses is correct.

5. What does this function do?


matlab.addons.toolbox.installToolbox

a) Install a .mlx file

b) Install a .mtbx file

c) Install a .mltbx file

d) Install a .tbx file

Answer: c

Explanation: The above function installs a toolbox into a system. Since a toolbox is a .mltbx file, only option Install a .mltbx file is correct.

6. License arguments for installing toolboxes are _______

a) Ignored

b) Shown

c) Do not exist

d) Depends on the system

Answer: b

Explanation: Irrespective of the system, a toolbox has a license agreement within it- it will be prompted during installation.

7. What is the output of the following code?


matlab.addons.toolbox.installToolbox(‘Lo.mltbx’)

a) Installs the Lo class into the directory

b) Uninstalls the Lo class from the directory

c) Uninstalls the Lo toolbox from the directory, if already present

d) Installs the Lo toolbox into the directory

Answer: d

Explanation: The above function installs a toolbox into the system. The toolbox should be present in the current directory.

8. What is the output of the following code?


matlab.addons.toolbox.installToolbox[‘Lo.mltbx’]

a) Error due to a directory

b) Installs the Lo toolbox into the directory

c) Logical Error

d) Syntactical error

Answer: d

Explanation: The input to the matlab.addons.toolbox.installToolbox command should be within parentheses. Here, [] is used which results in a syntactical error. It would’ve been a secondary error which won’t be checked even if it happens since the syntactical error will return the control.

9. What is the output of the following code?


matlab.addons.toolbox.installToolbox(Lo.mltbx,True)

a) Error

b) Ignores license file and installs the toolbox directly

c) Prompts the license file and installs the toolbox

d) Logical error

Answer: a

Explanation: The name of the toolbox file, given as an input to the command, is not given within ‘’. Hence, it’s not recognized as a file name and MATLAB returns an error.

This set of Tough MATLAB Questions and Answers focuses on “Toolbox Distribution – 2”.


1. What does the function matlab.addons.toolbox.installedToolboxes return?

a) A structure

b) A table

c) A structure of arrays

d) An array of structure

Answer: c

Explanation: The above command returns a structure of arrays which are the Name, Version and Guide of the toolboxes installed in the system. It can be converted to array form and then viewed properly.

2. What is the output of the following code?


ver Simulink

a) Shows the version of MATLAB

b) Shows the version of MATLAB and the Simulink Toolbox

c) Shows the version of the Simulink Toolbox

d) Shows the contents of Simulink Toolbox

Answer: b

Explanation: The ver function along with the name of a toolbox returns the version of the installed MATLAB version and the version of the toolbox.

3. What is the output of the above code?


ver Simulink Toolbox

a) Error

b) Shows the version of MATLAB

c) Shows the version of MATLAB and the Simulink Toolbox

d) Shows the version of the Simulink Toolbox

Answer: a

Explanation: The name of the toolbox is Simulink only. Hence, Toolbox written in the above code is an excess input and the output results in an error. The output would’ve been shows the version of MATLAB and the simulink toolbox if only Simulink was written.

4. A .mltbx toolbox is written in Java.

a) True

b) False

Answer: b

Explanation: A .mltbx toolbox is a toolbox which is written in the MATLAB environment only. Hence, the above statement is false.

5. A toolbox is same as a function.

a) True

b) False

Answer: b

Explanation: A toolbox has a multitude of function. It itself is not a function. It can be thought of as a header file.

6. What is the output of the following code?


matlab.addons.toolbox.uninstallToolbox[]

a) Error

b) Uninstalls the toolbox given in the input

c) Uninstalls all the toolboxes

d) Uninstalls the function given in the input

Answer: a

Explanation: The input to the above command is to be given within parentheses. If the input is given in the syntax shown above, it’ll result in an error.

7. What is the output of the following code?


matlab.addons.Toolbox.uninstalltoolbox()

a) Uninstalls the toolbox given in the input

b) Error

c) Uninstalls all the toolboxes in the system

d) Uninstalls the function given in the input

Answer: b

Explanation: There has been an error while spelling the command. It should be matlab.addons.toolbox.uninstallToolbox[], but it’s not so in the above code. Hence, this leads to an error.

8. What are the contents of the toolbox shown by the matlab.addons.toolbox.installedToolboxes command?

a) Name, Guid

b) Name, Version, Guid

c) Name, package, Guid

d) Name, package,

Answer: b

Explanation: The given command returns the properties of the installed toolbox, given by option name, version, guid. The guid is the toolbox identifier.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Performance and Memory – 1”.


1. The memory function is limited to _________

a) MS systems

b) Linux Systems

c) No system

d) Does not exist

Answer: a

Explanation: Typically, the memory function is present in MATLAB but is limited to the Microsoft Windows System. Hence, MS systems are correct.

2. What is p in the following code?


p=memory

a) A Structure of arrays

b) An array of structures

c) A stack

d) An array

Answer: a

Explanation: The function ‘memory’ returns 3 arrays, namely-

i. MaxPossibleArrayBytes

ii. MemAvailableAllArrays

iii.MemUsedMATLAB

And these are stored into p. So p is a structure of arrays.

3. When will the following be shown?


Limited by System Memory (physical + swap file) available.

a) In windows 64bit

b) In windows 32bit

c) In windows 64bit when mapping to a memory block is limited

d) In windows 32bit when mapping to a memory block is limited

Answer: c

Explanation: The above statement is shown in 64 bit systems. It is shown when there is insufficient memory in the system for mapping of all virtual addresses in the largest available block of the MATLAB process. Hence, Windows 64bit is correct option.

4. The memory used by MATLAB, shown in the output of the memory command, is ________

a) The total system memory allotted to MATLAB

b) The total physical memory allotted to MATLAB

c) The total space for only mathematical operations in MATLAB

d) The temporary storage allotted to MATLAB

Answer: a

Explanation: The memory function shows the total system memory allotted by MATLAB. It is the sum of the physical memory and potential swap file usage in the system.

5. What is the physical memory?


>>q.PhysicalMemory

ans = 

struct with fields:

        Available: 3.2158e+09

               Total: 8.5027e+09

a) RAM

b) Hard disk memory

c) ROM

d) Error

Answer: a

Explanation: The physical memory denotes the memory reserved in RAM for MATLAB. It can also be seen in the windows task manager. Hence, the correct answer is RAM.

6. Which of the following changes with time?


>>q.PhysicalMemory

ans = 

struct with fields:

        Available: 3.2158e+09

               Total: 8.5027e+09

a) Available Memory

b) Physical Memory

c) Available & Physical Memory

d) One at a time

Answer: a

Explanation: The physical memory denotes the RAM of the system where MATLAB is running. Hence, it doesn’t change but the available memory allotted to MATLAB changes.

7. Which of the following contains the system memory?


[p,q]=memory

a) p

b) q

c) It’s not returned

d) Error

Answer: b

Explanation: The system memory is stored in the structure q. Information regarding the system is returned as a second output by the memory command. So q is correct.

8. Which of the following contains the Physical Memory of the system only?


[p,q]=memory

a) p

b) q

c) It’s not returned

d) Syntactical error

Answer: b

Explanation: The physical memory of the system is an information regarding the system. That information are returned after the information regarding MATLAB is returned. Hence, they go to q.

9. Which of the following contains the memory used by MATLAB?


[p,q]=memory

a) p

b) q

c) It’s not returned

d) Error

Answer: a

Explanation: The memory command returns information regarding MATLAB prior to the system information and so the memory used by MATLAB is returned first. It’ll go to p and the correct option is p.

10. Which of the following contains the memory for the maximum possible array that can be made in MATLAB?


[p,q]=memory

a) q

b) p

c) It’s not returned

d) Error

Answer: b

Explanation: The memory command returns information regarding MATLAB prior to the system information and so the memory used by MATLAB is returned first. The maximum possible array is information regarding MATLAB and it’ll go to p and the correct option is p.

This set of Advanced MATLAB Questions and Answers focuses on “Performance and Memory – 2”.


1. Which of the following contains the memory for the virtual address space given to MATLAB?


[p,q]=memory

a) Error

b) p

c) There’s no virtual space for MATLAB

d) q

Answer: d

Explanation: The amount of memory allotted to the Virtual Address Space of MATLAB is given as an array to q. Hence, q is correct.

2. The function handle given to the timeit command cannot be defined within the timeit function.

a) True

b) False

Answer: b

Explanation: The function handle can be given as an input to the timeit command. It’s not necessary that we need a separate variable to declare a function handle.

3. The timeit function returns the time in ms.

a) True

b) False

Answer: a

Explanation: The timeit function returns the time in seconds. Hence, the above statement is false.

4. What is the output of the following code?


syms x;

timeit(@()sin(x))

a) The time required to compute the value of a sin

b) Error due to sin

c) Syntactical Error

d) Time required to initialize sin as a vector of symbolic elements

Answer: d

Explanation: Since x is declared as symbolic, the function sin will only initialize itself as sin, It doesn’t compute a specific value and hence the time required for initializing sin as a vector of symbolic elements is correct.

5. What is the output of the following code?


syms x;

timeit(@sin(x))

a) Syntactical Error

b) Logical Error

c) .0012

d) .0016

Answer: a

Explanation: The function handle has been declared with an error. A set of parentheses is missing. TH e function handle is defined as @sin. Hence, the above code will give an error.

6. Which of the following method increases the performance of operation?

a) Preallocation

b) Postallocation

c) It’s not possible to increase performance

d) Characterization

Answer: a

Explanation: The method of preallocation helps in increasing the performance of memory. It can be used to specifically increase the speed of the operation.

7. Is a==c?


>>a=timeit(@()sin(x));

>>b=cputime;

>>sin(x);

>>c=cputime-b;

a) No

b) Yes

c) Almost

d) Error

Answer: a

Explanation: The time calculated and assigned to c is usually more than that in a. This is because the cpu time increases in the third statement only. Hence the option, which says that a is not equal to c is correct.

8. What is the output of the following code?


a=timeit(()sin(x));

a) Error

b) .0012s

c) 12ms

d) .0016s

Answer: a

Explanation: There is an error in the above code. The function handle has been wrongly decalred since the ‘@’ is missing. Hence the option, which says there will be an error, is correct.

9. The amount of memory saved for swap files is more than the physical memory allotted for MATLAB.

a) True

b) False

Answer: b

Explanation: The latter is always greater than the former. This is because the physical memory is getting used up during operations.

10. The tick command starts a timer.

a) True

b) False

Answer: b

Explanation: The command is misspelled. The correct command is tic only. Hence, the above statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “System Commands – 1”.


1. The clipboard function cannot work without

a) Python

b) C

c) JAVA

d) Not present in MATLAB

Answer: c

Explanation: The command has been designed in MATLAB such that it won’t work in a system where the JAVA Oracle software is not present. Hence, the only correct option is JAVA.

2. What is the output of the following code?


clipboard('copy',poe)

a) Logical Error

b) Copies ‘poe’

c) Copies poe

d) Syntactical Error

Answer: d

Explanation: There is syntactical error in the following code. Since ‘poe’ is a string, it has to be declared within a pair of single inverted commas. Here it hasn’t been so which leads to an error and the correct answer is that there is a logical error.

3. What is the output of the following code?


clipboard(copy,’poe’)

a) Error

b) Copies poe

c) Copies poe to the MATLAB file

d) Copies poe to the MATLAB function

Answer: a

Explanation: ‘copy’ is a parameter passed to the function clipboard. It is a string so it should be enclosed within ‘’. But here, copy has been passed to the function without any enclosement which will characterize it as a string. Hence, this leads to an error.

4. What is the output of the following code?


clipboard[‘copy’,poe]

a) Error

b) Copies poe to a mlx file

c) Copies poe to a mat file

d) Copies poe to a mltbx file

Answer: a

Explanation: The input to the clipboard command has to be within parentheses. Since the above input has been given within [], it leads to an error.

5. What is the output of the following code?


clipboard(‘copy’,’poe’)

clipboard(‘paste’)

a) Prints poe

b) Prints ‘poe’

c) Prints error

d) Function not present in MATLAB

Answer: b

Explanation: ‘poe’ is a stirng. Hence, it will be printed within ‘’. The correct option is that ‘poe’ will get printed.

6. What is the output of the following code?


system(cmd)

a) Starts Command Prompt

b) Starts Command Prompt in MATLAB

c) Starts Command Prompt in a separate window

d) Error

Answer: d

Explanation: The input to the system command is a command which can be run through the OS. But the input int the above code isn’t given within ‘’. It should be within ‘’. Hence, this leads to an error.

7. What is the output of the above code?


system(‘cmd’)

a) Error

b) Starts Command Prompt in MATLAB

c) Starts Command Prompt in a separate window

d) Error

Answer: b

Explanation: A separate window isn’t opened for the command prompt. It starts in MATLAB only. Thus the correct answer is that the Command Prompt starts in MATLAB.

8. What is the output of the following code?


system('cd')

a) Shows the current directory

b) Shows the directory where MATLAB is located

c) Error

d) The function doesn’t exist

Answer: b

Explanation: cd is an OS command. The system command runs OS commands which are supported by the System. If we type ‘cd’ in Command Prompt, we get to know the current directory i.e. the path in the system where our control is currently present. Hence, here also, the current directory is shown.

9. What is the output of the following code?


system['cd']

a) Error

b) Syntactical error

c) Logical Error

d) Opens command prompt

Answer: a

Explanation: The input to the above system command should be given within parentheses. Since it has been given within [], it leads to an error.

10. What is the output of the following code?


system('date')

a) Shows the date in your system

b) Shows the actual date

c) Shows the date when MATLAB was installed

d) Error

Answer: a

Explanation: The above command shows the date which is displayed in the system. If it’s not the actual date, the command cannot differentiate and it’ll show what’s in your system. This is similar to the working in Command prompt and hence the correct answer is that it shows the date, currently saved, in the system.

This set of MATLAB Questions & Answers for Exams focuses on “System Commands – 2”.


1. Which of the following command can be used for DOS commands?

a) msdos

b) dos

c) ds

d) not possible in MATLAB

Answer: b

Explanation: The correct command to work on DOS commands is dos in MATLAB. This is because it is pre-defined in the libraries of MATLAB.

2. The input to the unix command should be within _________

a) 

b) {}

c) []

d) Is not available in MATLAB

Answer: a

Explanation: The unix command is defined in MATLAB to run unix based codes. The input to this command should always be within parentheses. Thus only  is allowed.

3. If the command, given as an input to the system command, gets executed, MATLAB returns a _________

a) 0

b) 1

c) True

d) False

Answer: a

Explanation: This the default return value of the system command. It will return a 0 if the command gets successfully executed. If not, it’ll return 1 and hence, only MATLAB will only return a 0.

4. What is the output of the following code?


system(date)

a) It shows the date but MATLAB returns 1

b) It doesn’t show the date and MATLAB returns 0

c) It doesn’t show the date but MATLAB returns 1

d) It shows the date but MATLAB returns 0

Answer: a

Explanation: The code din’t work properly since it wasn’t included within ‘’. But the date, updated in the system, does get printed. Due to the aforementioned error, it shows a 1 and the dat.

5. The input to the system command is not necessarily given within ‘’.

a) True

b) False

Answer: b

Explanation: The input to the system command has to be within ‘’. This is because the input has to be a command name and the command name is a string.

6. All system commands take input within parentheses.

a) True

b) False

Answer: a

Explanation: There isn’t a single system command in MATLAB which takes input within anything but parentheses. Hence, the above statement is true.

7. Windows Registry can be accessed by ___________

a) winqueryreg

b) winreg

c) windowsregistry

d) not possible

Answer: a

Explanation: The correct command to gain access to the windows registry is winqueryreg. The rest of the commands don’t exist.

8. How can we check the history of commands used?

a) By only clicking the up direction button

b) Using the commandhist command

c) Using the commandhistory command

d) Using the cmdhstry command

Answer: c

Explanation: It is not that we can check the history of the commands used, only, by clicking the upward direction button. It can be also checked by using the commandhistory function. Hence, using the commandhistory command is correct.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Wrong or Unexpected Output”.


1. What is the output of the following code?


cos(pi/2)

a) 0

b) Close to 0

c) less than 0

d) Undefined

Answer: b

Explanation: We’ve not declared pi as symbolic. The value of pi stored in MATLAB results in a calculation of cos by approximation and hence, the value evaluated will be significantly close to 0 but not exactly 0. Hence, we should be careful while evaluating the values of such trigonometrical functions.

2. What is the output of the following code?


sprintf(“5%”)

a) “5”

b) “5%”

c) 5

d) 5%

Answer: a

Explanation: To print the % as a character, we need to use %% within the sprintf function. Here, we haven’t used it twice so only 5 would get printed.

3. Why isn’t the answer 10.230?


>> sprintf("%1.3d", 10.23)

 ans = 

       "1.023e+01"

a) We’ve used %d

b) We’ve used “”

c) Character arrays are like this

d) Undefined answer

Answer: a

Explanation: If we had used %f, the answer would’ve been 10.230 since the number gets defined as a floating point number. But here, %d defines the number as an integer so the output becomes different.

4. How many times will the loop run?


for i={1:.1:5}

p=p+1;

end

a) 50

b) Infinite

c) 0

d) 1

Answer: d

Explanation: The control will exit the loop after the first iteration only so the loop never runs. This is because p is not defined previously or inside the loop.

5. What is the output of the following code?


A=[1 2 3 0; 4 5 6 8; 1 2 3 4; 1 3 4 5 ; 4 0 0 0 ];

length(A)

a) 5

b). 4

c) 5*4

d) 4*5

Answer: a

Explanation: The length function would return the highest length it finds in the input vector. Since, the input vector has 5 columns and 4 rows, it will return 5.

6. What will be the result after we press Return?


>> input('Ro !')

Ro ! Ho !

a) ans= Ho !

b) Error

c) No such command named input

d) Cannot be determined

Answer: b

Explanation: The input command only takes values as input i.e. it won’t take characters as input. Hence, when we press Return, there will be an error.

7. A student wants to find the following limit

matlab-questions-answers-wrong-unexpected-output-q7 but he writes the following code

limit/x^2,x,0)

What will he get?

a) a 2 /2!

b) a 2 /2

c) Error

d) -Inf

Answer: d

Explanation: He has written it wrong. The entire function is to be divided by x 2 but according to his code, only cos 2x gets divided by x 2 and hence it yields -Inf.

8. How long will ‘Hola !’ get printed?


>>input(‘Hola !’)

Hola !

a) Until a value is given as an input

b) Until a character is given as an input

c) Until anything is given as an input

d) Once

Answer: a

Explanation: The input command really starts an infinite loop. This means that until we give a value as an input, it’ll keep on printing ‘Hola !’- it’ll give an error if we give a character as an input.

9. What is the output of the following code?


syms x

limit(1/-x,x,-0)

a) NaN

b) Inf

c) 0

d) Syntactical error

Answer: a

Explanation: The bidirectional limit does not exist at x=0. It should not be expected that the answer is Infinite because the limit is infinite if we approach x=0 from left or right while we say that it does not exist at x=0.

10. Why did the following happen?


>> p

p = 

    "10"

>> p+1

ans = 

     "101"

a) p is a character array

b) p is binary

c) Error

d) Cannot be determined

Answer: a

Explanation: It’s seen that p=”10” which signifies that p is a character array only. Hence, adding 1 to it is merely adding another element into the character array so one shouldn’t expect it to be 11.

11. Why di the following happen?


>> sprintf("   %   ")

ans = 

     "  "

a) Error

b) % is not recognized

c) % is an operator

d) Cannot be determined

Answer: b

Explanation: To print a ‘%’, we need to put ’%%’ within the double quotes while in the above case, we observe ‘%’. This is not recognized by the sprintf command and so, the output is a blank character array.

12. What is the output of the following code?


det([1 2 3; 4 5 6; 7 8 9])

a) Error

b). 0

c) -0

d) A very small value

Answer: d

Explanation: Any determinant in MATLAB is calculated using the LU decomposition method which eventually results in rounding off errors in case of singular matrices. Since the given matrix is singular, it will give a very small value.

13. What is the output of the following code?


 >> { 1 2}

 ans = 

   1*2 cell array

     [1]   [2]

>> ans+{3 4}

a) { 1 2 3 4}

b)


     { 1 2

       3 4}

c) { 4 6}

d) Error

Answer: d

Explanation: Cellular arrays cannot be added in MATLAB. Hence the above code will result in an error. if the arrays were within [], the would’ve been simple 1d vectors which could be easily added.

14. What is the output of the following code?


tf2zp({1 2}, {2 1})

a) 0

b) Returns the zeros and poles of the transfer function /

c) Syntactical Error

d) Logical Error

Answer: c

Explanation: The input to the tf2zp command cannot be cellular arrays. But we’ve used {} in the above code and this leads to a syntactical error in MATLAB.

15. What is the output of the following code?


syms ‘t’,’p’;

a) Both t and p are defined as symbolic

b) Only t gets defined as symbolic

c) Only p gets defined as symbolic

d) Nothing happens

Answer: b

Explanation: There is a syntactical error in using syms. Only t gets defined while p gets initialized to the ans variable so it’s not defined as symbolic. This is due to the ‘ , ‘ present which leads to this error, we must remove them, to declare multiple characters as symbolic variables.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Syntax Error – 1”.


1. What is the error in the following?


input(“pop”)

a) None

b) “”

c) Parentheses

d) No such command

Answer: b

Explanation: The input to the input command should be within ‘’ and not “”. Double-inverted commas will lead to a syntactical error in MATLAB.

2. What is the error in the following code?


for i={1: 10}

p=a+1

end

a) None

b) {}

c) The : operator

d) Cannot be determined

Answer: a

Explanation: MATLAB won’t give any error. but the loop will only run once because we have a syntactical error while defining the conditions for the loop.

3. What is the output of the following code?


limit[1/x,0]

a) NaN

b) Inf

c) Syntactical Error

d) Logical error

Answer: c

Explanation: The input to the limit command should be within parentheses. But here, the input is given within []. This leads to an error in MATLAB.

4. What is the output of the following code?


length{ 1 2 }

a) Error due to space after 2

b) Error due to {}

c) Syntactical Error

d) 2

Answer: c

Explanation: The input to the length function has to be within a parentheses. We don’t see the parentheses here, and we’ll find that this leads to an error in MATLAB.

5. What is the output of the following code?


limit((1 + 1/n)^n,n=Inf)

a) e

b) exp

c) Syntactical Error

d) Cannot be determined

Answer: c

Explanation: The correct syntax would be to simply state the limiting value as Inf. This is for new versions of MATLAB. The above code would result in a syntactical error.

6. What is the output of the following code?


A={1 2 3 4}

sum(A)

a) Error

b) 10

c) { 10 }

d) Logical Error

Answer: a

Explanation: The sum function doesn’t work on cellular arrays. So the vector A is to be placed within [] to avoid this kind of error.

7. What is the output of the following code?


limit({sin(x)/x},x,Inf,right)

a) 0

b) Inf

c) Syntactical error

d) Error due to inconsistency in approaching limit

Answer: c

Explanation: There is syntactical error in the above code snippet. The input, right, should be within a pair of single inverted commas. If that was so, there is still error due to inconsistency in approaching the limiting value because we cannot approach positive Infinity from it’s right hand side.

8. What is the output of the following code?


mean({1 2 3})

a) 2

b) Logical Error

c) 1

d) Syntactical Error

Answer: d

Explanation: Since the mean command uses the sum command, it also cannot accept cellular arrays as input since this input will go to the sum command first. Hence, the above code will give a syntactical error. Now, if we had given the input, within parentheses, within []- the output would’ve been 2 only.

9. What is the output of the following code?


det({1 2 3; 4 5 6; 7 8 9})

a) 0

b) Syntactical Error

c) A very small value

d) Cannot be determined

Answer: b

Explanation: The input to the det command cannot be a cellular array. Since we have given the vector within {}, it results in an error. The output would have been very small value if the mtrix was given within [].

10. What is the output of the following code?


(1 2);

a) A cellular vector of dimension 1*2

b) A vector of dimension 1*2

c) A matrix of dimension 1*2

d) Error

Answer: d

Explanation: To create a vector, one needs to give the elements within [] and not within parentheses. Hence, the above code will result in a syntactical error.

11. What is the output of the following code?


p=[1 3 2]; roots[p];

a) Syntactical Error

b) Undefined roots

c) -2,-1

d) Cannot be determined

Answer: a

Explanation: The input to the roots command has to be within parentheses. Here, it’s given within [] so it’ll result in a syntactical error. If the input was given within parentheses, the output would’ve been -2,-1.

12. What is the output of the following code?


poly[ 1 2 3]

a) x + 2x + 3x 2

b) x 3 + 2x 2 + x

c) Error

d) Cannot be determined

Answer: c

Explanation: The input to the poly command has to be within parentheses. If the input is a vector, one can define the vector, prior to giving it as an input, or give the input like poly.

13. What is the output of the following code?


polyint[{1 2 3}]

a) Syntactical error due to []

b) Syntactical Error due to {}

c) Logical Error

d) [1/2,1,3]

Answer: b

Explanation: The answer would’ve been d. But the input to the polyint command is a cellular array and this results in a syntactical error. But firstly, the input to the polyint command should be within parentheses. But here, the input is within [] which is the first error MATLAB finds.

14. What is the output of the following command?


>> x={1 2 3};

>> t=[1 2 3];

>> plot(x,t)

a) plots a ramp function

b) plots r-r

c) Error due to plot

d) Error due to x

Answer: d

Explanation: In the above code, x is a cellular array. It will create an error in the working of the plot command since the plot command cannot plot values in cellular arrays. Hence, there is a syntactical error while defining x for the plot command.

15. The input to the polar command is not necessary to be within parentheses.

a) True

b) False

Answer: b

Explanation: The polar command is pre-defined in MATLAB and it only takes inputs within a parentheses only. Hence, the above statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Syntax Error – 2”.


1. What is the output of the following code?


for ( i=1:10 )

if{i<3}

break

end

end

a) Syntactical Error

b) Logical Error

c) i=1

d) i=2

Answer: a

Explanation: There is a syntactical error in the above code while giving the condition for the if structure. Hence, this leads to an error in MATLAB. If the condition was given within parentheses, the output would’ve been option i=1.

2. What is the final value of i?


for i=[1:10]

end

a) 0

b) 1

c) Error

d) 10

Answer: c

Explanation: The assignment of the index value is done within []. This leads to a syntactical error. We can put it in parentheses or just write it after for then the output would’ve been 10.

3. What is the output of the following code?


syms p q;

x=p+2q;

findsym[x]

a) Syntactical Error

b) p,q

c) No such command

d) p

Answer: a

Explanation: The findsym command takes input within parentheses. But here we have used the [] which leads to a syntactical error. The output would’ve been p,q if the input, x, was given within parentheses.

4. What is the output of the following code?


syms p q;

x=p+2*q;

diff[x];

a) 1

b) 0

c) Syntactical Error

d) Logical Error

Answer: c

Explanation: The output would’ve been 1 if the input to the diff command was given within parentheses. But the input has been given within [] which results in a syntactical Error.

5. What is the output of the following code?


syms pi;

p=2sin[pi]/cos[pi] + tan[3pi];

a) 0

b) A value very close to 0

c) Syntactical Error

d) Error in the expression

Answer: d

Explanation: There would’ve been a syntactical error but we have not put a * sign between 2 and sin[2*pi]. This is the first error MATLAB finds and returns this as an error. There is also syntactical error since the input to the sin, cos or tan command should always be within parentheses only.

6. What is the output of the following code?


solve[‘x^2+1=0’]

a) x=j,-j

b) x=+i,-i

c) Syntactical Error

d) Logical Error

Answer: c

Explanation: The input to the solve command should always be within parentheses. Since, here, we’ve given the input within [], this will result in a syntactical error. The output would’ve been x=+i,-i if the input was given in parentheses.

7. What is the output of the following code?


syms [p,q]

a) Establishes p and q as symbolic variables

b) Syntactical Error

c) Logical Error

d) Only p is symbolically defined

Answer: b

Explanation: We cannot declare vectors as symbolic. If we need to declare multiple variables as symbolic, we can write each variable with space in between like- syms p q and the output would’ve been establishes p and q as symbolic variables.

8. Vectors defined by [] can be cellular vectors.

a) True

b) False

Answer: b

Explanation: Cellular vectors can only be defined by using a {}. If they are defined using [], it becomes a 1-D vector which is different from cellular arrays.

9. What is the output of the following code?


tf2zp({1 2}, {2 1})

a) 0

b) Returns the zeros and poles of the transfer function /

c) Syntactical Error

d) Logical Error

Answer: c

Explanation: The input to the tf2zp command cannot be cellular arrays. But we’ve used {} in the above code and this leads to a syntactical error in MATLAB.

10. What is the output of the following code?


error{“404”}

a) 404

b) Error in the command

c) Error 404

d) Syntactical Error

Answer: d

Explanation: The syntactical error in the above code is the fact that the input to the command is given within {}. It should be given within parentheses- then the output would’ve been option error in the command only.

11. What is the output of the following code?


warning(“a”)

a) Warning: a

b) Error in the code

c) Syntactical Error

d) Logical Error

Answer: c

Explanation: There is a syntactical error in the above code. The input should be present within a pair of single inverted commas- to signify the warning message as a string. The output would’ve been option Warning: a in that case.

12. What is the output of the following code?


syms ‘t’,’p’;

a) Both t and p are defined as symbolic

b) Only t gets defined as symbolic

c) Only p gets defined as symbolic

d) Nothing happens

Answer: b

Explanation: There is a syntactical error in using syms. Only t gets defined while p gets initialized to the ans variable so it’s not defined as symbolic. This is due to the ‘ , ‘ present which leads to this error, we must remove the, to declare multiple characters as symbolic variables.

13. What is the output of the following code?


poly{1,2}

a) Syntactical Error

b) 1 3 2

c) Cannot be determined

d) 0

Answer: b

Explanation: The poly command returns the co-efficients of the polynomial according to the given input, the inputs being the roots of the command. The output would’ve been 1 3 2 but the input is given within {} which leads to a syntactical error. It should be provided within parentheses.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Spelling Error – 1”.


1. What is the output of the following code?


T=-9:0:9;

STEM(T);

a) Error

b) Plots a ramp function from 0 to 9 units in time

c) Plots a discrete function

d) Logical Error

Answer: a

Explanation: MATLAB is sensitive to uppercase and lowercase letters. The stem command has been written in uppercase letters so it is not recognized by MATLAB. It should be written in lowercase letters and then the output would be Plots a discrete function.

2. What is the output of the following code?


N=Input[‘’];

a) Ask for an input from the user

b) Asks for an input from the user which has to be kind of number

c) Input command does not exist

d) Syntactical Error

Answer: c

Explanation: There is a syntactical error since the input to the input command should be within parentheses. But the first error MATLAB notices is that it doesn’t recognize the command due to the Uppercase I. This leads to an error.

3. Given below is a part of a very big program. What is the output?


A=[1 2 3];

mean(a);

a) Error

b) 2

c) Cannot be determined

d) The mean of a

Answer: c

Explanation: Since the variable a is not defined, the input to the mean command does not exist. This is a very common mistake and it should be checked upon. The variable is ‘A’ and if the input was mean, the output would’ve been 2. But here there is an error.

4. A student is trying to plot multiple plots in the same window. But the following code doesn’t allow him to do that. What is the error?


t=0:1:9;

stem(t);

hld;

stem(t^2);

a) Error in t^2

b) Error in hld

c) No error

d) Error in stem

Answer: b

Explanation: There will be an error in t^2 since t is a vector. But the first error MATLAB observes is the hld, it is supposed to be hold. The hold command results in holding the window of the current plot of stem so that multiple commands can be plotted in it. But since it has been misspelled.

5. What is the output of the following code?


Recpulse(1,9)

a) A column vector of 1’s of length 9

b) A column vector of 1’s of length 10

c) A row vector of 1’s of length 9

d) Error

Answer: d

Explanation: The command is spelled wrong, it should’ve been rectpulse, with the R in lowercase. If the command was rectpulse, the output would’ve been a column vector of 1’s of length 9.

6. What is the output of the following code?


tripulse(3)

a) Error

b) 0

c) 1

d) 2

Answer: a

Explanation: There is an error in the following code. The tripulse command is misspelled, it should be tripuls. The output would’ve been 0 if there was no spelling error.

7. What is the output of the following code?


Mean([1 2 3 4])

a) Error due to the Mean command

b) 2.5

c) 2 and 3

d) Syntactical Error

Answer: a

Explanation: The actual command is ‘mean’ which would yield 2.5 as output. But the uppercase M, int the given command, results in an error since MATLAB doesn’t recognize it. Since there is no syntactical error- even if there was, MATLAB would’ve first returned the first error.

8. What is the output of the following code?


lengths([1 2 3])

a) 3

b) 1*3

c) Error due to lengths command

d) Cannot be determined

Answer: c

Explanation: The length command is used but since we have an extra ‘s’ after it, the command is not recognized by MATLAB. Hence, this leads to an error. Otherwise, the output would’ve been 3 only.

9. What is the output of the following code?


sten([0:1:4],2*ones(1,5)]

a) A discrete step function

b) A discrete pulse function from 0 to 4 units in time

c) A ramp function

d) Error

Answer: d

Explanation: The stem command is misspelled as sten which leads to an error. The output would’ve been a discrete pulse function from 0 to 4 units in time but due to this, there is an error as an output.

10. There are a few commands, in MATLAB, which can be used by ignoring the cases.

a) True

b) False

Answer: b

Explanation: All the commands, predefined in MATLAB, are in lowercase and they cannot be called by uppercase letters. Hence, the above statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Spelling Error – 2”.


1. What is the output of the following code?


plot([0:1:4],one(1,5))

a) A pulse function from 0 to 4 units in time

b) A step function

c) A ramp function

d) Error

Answer: d

Explanation: The ones command isn’t completely written i.e an s is missing which leads to an error. The output would’ve been a pulse function from 0 to 4 units in time but due to this, there is an error as an output.

2. What is the error when MATLAB finds an unknown command or function?

a) Undefined function

b) Undefined function or variable ‘command name’

c) Undefined variable or function

d) Undefined function or variable ‘command name’

Answer: b

Explanation: The error message shown when a command is not recognized by MATLAB is the undefined function or variable ‘command name’. This is pre-defined in MATLAB.

3. What is the output of the following code?


stem([0:1:1],zero(1,2))

a) An empty graph extending from 0 to 1 unit in x axis and 0 to 2 in the y axis

b) An empty graph extending from 0 to 1 unit in y axis and 0 to 2 in the x axis

c) Syntactical Error

d) Error in zero command

Answer: d

Explanation: The zeros command isn’t fully written, an s is missing at the end and this leads to an error in MATLAB. If the ‘s’ was not missing.

4. What is the output of the following code?


sine(pi/2)

a) Error due to pi

b) Error due to sine

c) 1

d) Cannot be determined

Answer: b

Explanation: The output would’ve been 1 but the command to find the sine of an angle is sin whereas we have added an extra ‘e’ in the above command. MATLAB won’t recognize this command and will give an error in the code.

5. A user defined function can be used by neglecting case sensitivity.

a) True

b) False

Answer: b

Explanation: A user-defined command cannot be used by neglecting case sensitivity. MATLAB won’t be able to recognize the particular m.file and if we call the function by neglecting case sensitivity, it will result in an error.

6. What is the output of the following code?


decon([6 12 18],[ 1 2 3])

a) 6

b) 0

c) Cannot be determined

d) Error

Answer: d

Explanation: The deconv command isn’t written completely, a ‘v’ is missing at the end. If the ‘v’ was not missing, the output would’ve been 6. But here, MATLAB returns an error.

7. What is the output of the following code?


syms t;

ipulse([1],[1 0])

a) A step function

b) A ramp function

c) Logical error

d) Spelling error

Answer: d

Explanation: The answer could’ve been a step function. But there’s a spelling error in the above code, an ‘m’ is missing- the entire command would be ‘impulse’.

8. What is the output of the following code?


syms t; 

stip([1],[1 0 0])

a) A step function

b) A ramp function

c) Logical error

d) Spelling error

Answer: d

Explanation: There is a spelling error in the above code. The real command is ‘step’ but it has been misspelled as ‘stip’ which results in an error. If there was no error, the answer would’ve been a parabola.

9. What is the output of the following code?


laplacet(t^2);

a) Error in the input

b) Error in the command

c) 2/s^3

d) Cannot be determined

Answer: b

Explanation: There is an error in the input since t is not defined as symbolic. But the command has been misspelled as ‘laplacet’- the t is extra and it should not be there. The answer would’ve been 2/s^3 if the command was written properly and t was defined as symbolic.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Laplace Transform – 1”.


1. The default Laplace transform, of functions, computed by MATLAB is __________

a) Unilateral

b) Bilateral

c) Multipolar

d) Cannot be computed

Answer: a

Explanation: The default laplace transform computed by MATLAB is the Unilateral Laplace transform. Bilateral Laplace transform can be computed separately but it’s not the default process.

2. The laplace transform of step function, u, can be calculated by using _____

a) syms t; laplace

b) laplace

c) laplace

d) sym t; laplace

Answer: a

Explanation: The laplace command won’t understand 1 is a unit function. Also, if we don’t define t as symbolic, it won’t be able to understand ‘t/t’. Finally, sym t doesn’t properly define t for using it in the laplace command so we need to write t=sym while using the sym command. Instead of this, we write syms t to define it, as a symbolic variable, for the laplace command.

3. How many time domain representations of the following signal is possibly stable?


F(s)=2s+4/(s2+4s+3)…. Where s is the Laplacian frequency

a) 2 for sigma>-1

b) 2 for sigma>-3

c) Only 1 for -3<sigma<-1

d) 1 for sigma<-1

Answer: c

Explanation: One of the conditions in condition for stability is that the R.O.C of the signal should include the imaginary axis. In options 2 for sigma>-1 and 2 for sigma>-3, the condition is satisfied but there is only 1 time domain representation in such case. We also have option Only 1 for -3<sigma<-1 which is true for the given range of sigma. Option 1 for sigma<-1 is not stable since the imaginary axis is not included.

4. The Transfer Function of an L.T.I. system is ___________

a) the impulse response with 0 initial conditions

b) the impulse response with some initial conditions

c) the ramp response with 0 initial conditions

d) the step response with 0 initial conditions

Answer: a

Explanation: The transfer function of the system is determined with 0 initial conditions. Since it’s the laplace transform of the impulse response, the impulse response should not have any initial conditions.

5. What will be the output of the following code?


syms ‘-t’; laplace(4*(-t))

a) Syntactical Error

b) The laplace transform of the time reversed ramp function.

c) -4/s 2

d) Logical Error

Answer: a

Explanation: We cannot define ‘-t’ as symbolic i.e. we can only define an alphabet as symbolic but not a character symbol like ‘-‘ or ‘+’. This leads to a syntactical error. There is no logical error.

6. What is the output of the following code?


(z,p)=tf2zp([1],[1,0])

a) Error

b) z=0,p=0

c) z=0,p=1

d) z=1,p=0

Answer: a

Explanation: The output would’ve been option b but we have given z,p within parentheses. They should be placed within [] to get the proper output since the command tf2zp evaluates.

7. The final value theorem is applicable if __________

a) Poles lie on right half of s plane

b) Poles lie on left half of s plane

c) Poles lie on the imaginary axis

d) Zeros lie on left half of s plane

Answer: b

Explanation: If poles don’t lie on the left half of s-plane, the system is not stable. An unstable system yields an erroneous final value which i.e an erroneous steady state response. They also cannot lie on the imaginary axis. Hence, the theorem is applicable only in case of poles lie on right half of s plane.

8. What is the output of the following code?


laplace[‘t^t’]

a) A gamma function

b) Error due to []

c) Error due to ‘’

d) Cannot be determined

Answer: b

Explanation: The first error MATLAB observes is that the input to the Laplace command is given within []. It should always be within parentheses. The next error is that the input is given within ‘’ which makes the input act like a stirng and this is also an error. Since MATLAB returns the first error, the output would be error due to [].

9. If f=f 1 +f 2 , the laplace transform of f exists if f 1  and f 2  does not have the same R.O.C.

a) True

b) False

Answer: b

Explanation: If the functions f 1  and f 2  do not have the same R.O.C., the laplace transform of f won’t exist. This is because f is a result of addition of both the function and if one of them doesn’t exist, the entire function would collapse.

10. What is the output of the following code?


[r,p,k]=residu(z,p);….. Assuming z and p are vectors of unequal length

a) Returns the transfer function as partial fractions

b) Returns the transfer function variable

c) Returns an error

d) Cannot be determined

Answer: c

Explanation: The function is wrongly spelled, it should be residue and this leads to an error. The output would’ve been returns the transfer function as partial fractions if the function was correctly spelled.

11. What is the output of the following code?


(r,p,k)=residue(z,p);….. Assuming z and p are vectors of unequal length

a) Returns the residue and poles for the partial fractions

b) Returns the zeros and poles

c) Returns a syntactical error

d) Cannot be determined

Answer: c

Explanation: Since the residue function returns multiple outputs, the output should be taken in a vector. But here, the output is taken within parentheses and this leads to an error in MATLAB. If the output was taken within [].

12. What is the default variable used to represent the laplace transform in the output?

a) s

b) z

c) S

d) p

Answer: a

Explanation: The default variable used to represent the laplace transform of a function, by the laplace command, is ‘s’. This can be altered by giving different input to the laplace commad.

13. A causal system is stable if the pole lies on the right half of the s-plane.

a) True

b) False

Answer: b

Explanation: If the pole lies on the right half of the s-plane, it will be seen that the laplace transform is not absolutely converging and hence, the system won’t be stable. Thus the above statement is false.

14. The laplace transform of the following function.


f(t)= 3 when t=[0-5] 

     =  0 otherwise is….. L denotes Laplace Transform

a) L{3u-3u}

b) L{3u[t+5]-u[t-5]}

c) L-3u)

d) L

Answer: c

Explanation: The above function can be represented in terms of step functions. Only option L-3u) is the correct representation of the given function in terms of step functions and thus the Laplace transform of that function only will yield the laplace transform of the given function in MATLAB.

15. What will be the output of the following code?


ilaplace(‘1/s’)

a) Error

b) 1

c) u

d) 0

Answer: a

Explanation: The output would’ve been 1, representing u i.e. the step function. But the input has been given within ‘ ’ which leads to an error since the function is now represented as a string.

This set of MATLAB written test Questions & Answers focuses on “Laplace Transform – 2”.


1. An L.T.I. system is stable if _______

a) Poles lie on left half of s-plane

b) The R.O.C. encompasses the imaginary axis

c) The poles lie on the left half of s-plane and the R.O.C. encompasses the imaginary axis

d) Cannot be determined

Answer: d

Explanation: An L.T.I. system is stable if and only if both the conditions Poles lie on left half of s-plane and R.O.C. encompasses the imaginary axis are satisfied.

2. The final value of the following transfer function is ________


F(s)= 2/s(s-824)

a) Not calculable

b) -1/412

c) 0

d) 1

Answer: a

Explanation: We find that the pole of the given transfer function lies in the right half of s-plane. The system is not stable so we cannot apply the final value theorem and the final value is not calculable.

3. The number of inverse lapalace transform of a function is equal to ________

a) the number of poles

b) the number of poles+1

c) the number of poles-1

d) cannot be determined

Answer: b

Explanation: It is seen that the number of possible inverse laplace transform of any function is equal to the number of poles it has +1. Considering a function F=A/s+1 + B/s+3=F 1 +F 2 , the inverse laplace transform would exist if the inverse laplace transform is absolutely converging in a region. There are 3 regions that can have an absolutely converging state for F 1  and F 2  simultaneously and hence, only option the number of poles+1 is correct.

4. The laplace transform method used to solve a differential function is ____ than the classical way.

a) Easier

b) Harder

c) Moderately difficult

d) Relatively difficult

Answer: a

Explanation: The classical way is more tideous while the laplace transform allows it to represent the differential function in an algebraic form. Thereafter, the inverse laplace transform does the work.

5. What is the output of the following code?


laplace[t,t,2]

a) 1/16

b) Error

c) 1/s^2

d) Cannot be determined

Answer: b

Explanation: The input to the laplace command cannot be within []. Since the input is given within [], this will result in an error. The output would’ve been option 1/16 if the input was given within parentheses.

6. The laplace transform of a cascaded system is defined if _______

a) the individual systems have a common R.O.C.

b) the individual systems doesn’t have a common R.O.C.

c) the impulse response of each system is defined

d) cannot be determined

Answer: a

Explanation: It’s necessary for the individual systems, in a cascaded system, to have a common R.O.C.- otherwise the Laplace transform won’t be absolutely converging in a region. If ti doesn’t converge, the transform is not defined.

7. The inverse laplace transform of a function in s-domain is the transfer function of the system.

a) True

b) False

Answer: b

Explanation: The transfer function is an s-domain representation of the impulse response of a system. So, the inverse laplace transform of a function might generate the impulse response of a system but the transfer function is represented in s domain and so the above statement is false.

8. The following output is defined for _______


>>ilaplace(1/s)

>> ans=

        1

a) t>0

b) t>=0

c) for all t

d) t<0

Answer: b

Explanation: The inverse laplace transform, in MATLAB, yields the time domain representation of the function for which the function is causal. Hence, option t>=0 is correct only.

9. The differential equation d2p/dt2=9t has a solution.

a) 3/(2*t 3 )

b) cannot be determined

c) no solution

d) ilaplace(9/s 4 )

Answer: b

Explanation: It is not stated whether there are any initial conditions or not for the given differential equation. Hence, it’s not possible to state the solution of the above equation. If the initial conditions are 0, the laplace transform of the given equation yields- s 2 p=9/s 2 and a solution is reached by using option ilaplace(9/s 4 ) in MATLAB and that solution is option 3/(2*t 3 ). But we cannot talk about a solution until we know about the existence of the initial conditions.

10. What is the output of the following code?


syms t; laplace(-t/t)

a) The laplace transform of u

b) The laplace transform of -u

c) The laplace transform of -u

d) The laplace transform of -u

Answer: d

Explanation: The above command simply evaluated the laplace transform of -u i.e. it’ll invert the step function due to the ‘-‘ sign but will evaluate the laplace transform for t>=0 only.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Time Response of Control Systems – 1”.


1. The transient response, yt, of a system becomes ____ as t tends to infinity.

a) 0

b) 1

c) Infinity

d) Undefined

Answer: a

Explanation: The transient response of a system slowly becomes 0 as the time, for which the input is given, increases. Finally, the total response of the system is only the steady state response.

2. The steady state value of a system is _____ it’s a transient response.

a) dependent on

b) independent of

c) greater than

d) not observable from

Answer: a

Explanation: The steady state value of a system is dependent on the transient response of the system since every system goes through a transient state before reaching the steady state. In a design of control systems, we’ve to control the transient response to reduce the steady state error, which occurs due to undesirable transient response.

3. Delay time is the time required by a system to reach a quarter of its steady state value.

a) True

b) False

Answer: b

Explanation: The delay time is defined as the time required by the system to reach half of its steady state value. Hence, the above statement is false.

4. For non-unity feedback system, the error is calculated with respect to the reference signal.

a) True

b) False

Answer: b

Explanation: The error will be calculated with respect to the actuating signal i.e the feedback signal is either added or subtracted from the reference signal and the error is calculated with respect to the resultant signal. Hence, the above statement is false.

5. What is the output of the following code?


>>p=[0 1];

>> q=[ 1 -1 0];

>> step(p,q)

a) An unstable response

b) A stable response

c) A marginally stable response

d) A marginally unstable response

Answer: a

Explanation: We observe that the vector containing the poles, in the step command, signifies a second order system with a pole on the right half of the s-plane. This makes the system unstable and leading to an unstable response.

6. Which of the following command will reveal the damping ratio of the system?

a) damp

b) damp[]

c) damping{}

d) dr

Answer: a

Explanation: damp is the correct command to find the damping ration of the system. We need to represent the system by it’s transfer function and give it as an input to the damp command. The input has to be within parentheses.

7. What is the output of the following code?


>>p=[ 1 0 1];

>> q=[  -1 1];

>> step(p,q);

a) An unstable step response

b) A stable step response

c) Error

d) A marginally unstable response

Answer: c

Explanation: We observe that the vector containing zeros, in the step command, reveals that the given system has more zeros than poles. This system output goes to infinity for increasing frequencies and hence MATLAB cannot plot the step response. Thus it’ll give an error.

8. What is the output of the following code?


tf({1},{1 1})

a) Error

b) 1/s+1

c) s+1/1

d) 1/s

Answer: a

Explanation: The input vectors, to the tf command, are cellular arrays. This leads to an error because the tf command only takes row vectors. If the vectors were given within [], the output would’ve been 1/s+1.

9. If the damping factor is zero, the unit-step response is

a) Purely sinusoidal

b) Ramp function

c) Pulse function

d) Impulse function

Answer: a

Explanation: The generalized time response of a second order control system reduces to a purely sinusoidal function when the damping factor is zero. This is because the damping ratio becomes 0. Hence, the correct option is purely sinusoidal.

10. What is the output of the following code?


impulse([1],[1 1])

a) e-t*u

b) e-t*u

c) e-t*u

d) e+t*u

Answer: a

Explanation: We observe that the given pole zero vectors are suggesting a transfer function of 1/s+1. The impulse response of this system is simply the inverse laplace transform which yields e-t*u as the correct answer while the rest are incorrect.

11. If the damping ratio is equal to 1, a second-order system is _________

a) having maginary roots of the characteristic equation

b) underdamped

c) critically damped with unequal roots

d) critically damped with equal roots

Answer: d

Explanation: The time response of a system with a damping ratio of 1 is critically damped. But the roots of the characteristic equation will be equal and equal to negative of the natural undamped frequency of the system.

12. From the following graphs of the generalized transfer function 1/s+a, which plot shows a transfer function with a bigger value of a?

matlab-questions-answers-time-response-control-systems-1-q12

a) Blue plot

b) Red plot

c) Yellow plot

d) Purple plot

Answer: d

Explanation: As the value of a increases, the inverse laplace transform of the given transfer function suggests that the e-at value is reducing. Hence for a higher a, the graph reaches a 0 earlier. From the given figure, the purple plot reaches the steady state faster so purple plot is correct only.

13. From the following graphs of the generalized transfer function 1/as2, which plot shows the transfer function for a higher a?

matlab-questions-answers-time-response-control-systems-1-q13

a) Blue

b) Red

c) Yellow

d) Purple

Answer: d

Explanation: The impulse response of the given transfer function is a ramp function of slope 1/a. If a increases, the slope decreases. Hence, from the above figure, purple is the correct one.

14. If the damping factor is less than the damping factor at critical damping, the time response of the system is ___________

a) Underdamped

b) Overdamped

c) Marginally damped

d) Unstable

Answer: a

Explanation: If the damping factor is less than the damping factor at critical damping i.e. the natural frequency, the damping ratio becomes less than 1. This makes the system underdamped since the response of the system becomes a decaying sinusoid in nature.

This set of MATLAB Objective Questions & Answers focuses on “Time Response of Control Systems – 2”.


1. The steady state error of the system with a forward path transfer function G=13/ and with a parabolic input is _______

a) Infinite

b) 0

c) -Infinite

d) Undefined

Answer: a

Explanation: The given system has no poles at s=0. This means that for a parabolic input, the parabolic error constant is 0. Hence, the steady state error will go to infinity. Thus option Infinite is correct only.

2. For a step response of the system 1/s2+1, the maximum overshoot is __________

a) 1

b) 0

c) Infinite

d) 2

Answer: d

Explanation: For a step response of a second ordered system, the maximum overshoot depends only upon its damping ratio. Since the given system is a second ordered system, the maximum overshoot is a function of its damping ratio. But here, the damping ratio is 0 so the system has a maximum overshoot of 1.

3. What is the gain of the system derived from the following code?


tf[1,100]

a) 1/100

b) s/100

c) 1/100s

d) Error

Answer: d

Explanation: The input to the tf command should be within parentheses. Here we’ve used [] which leads to an error. If the input was within parentheses, the gain is .01 which is a static gain.

4. What is the output of the following code?


step(impulse(1,[1 0]))

a) A ramp function

b) A parabolic function

c) A step function

d) Error

Answer: d

Explanation: The input to the step command should be the poles and zeros of the transfer function. This way of giving input is not possible since the impulse command generates a graph and we are really giving a graph as an input to the command which leads to an error. Although, the impulse command generates a step function and the step response of a step function is a ramp function- here there will be an error.

5. What is the output of the following code?


r.DampingRatio = 0;

overshoot = getOvershoot(r);

a) 100

b) 0

c) 1

d) Error

Answer: d

Explanation: To use the getOvershoot command, we need to instantiate the sdp.requirements.DampingRatio class. Since the class is not instantiated, the command won’t be discovered by MATLAB and it will give an error.

6. Which of the following command gives the step response characteristics of a control system?

a) stepinf

b) stepinfo

c) stepinfo[]

d) step

Answer: b

Explanation: The stepinfo command is pre-defined in MATLAB to get the step response characteristics of a control system. The input is to be given within parentheses and not []. The step command gives the output graph of the step response and it doesn’t reveal the characteristics explicitly.

7. Which of the following command generates the impulse response of a system which has more zeros than poles?

a) impulse

b) impulse[]

c) impulse{}

d) No such command

Answer: d

Explanation: There isn’t any command defined in MATLAB which will compute the response of a system having more zeros than poles. Such a system is unstable at higher frequencies.

8. Which of the following command generates the transfer function of a system?

a) tf

b) tf[]

c) tf{}

d) No such command

Answer: a

Explanation: The command to get the transfer function of a system is tf. The input to the command should be within parentheses. Hence, option tf is correct only.

9. What is the output of the following code?


step([1],[1 0 0])

a) A parabola

b) A ramp function

c) A step function

d) An impulse function

Answer: a

Explanation: We observe that the given input vectors suggest that the transfer function is actually 1/s 2 . This means that the transfer function is a ramp function. The step response of a ramp function is a parabola. Hence, a parabola is correct.

10. The time constant of a system is ________

a) equal to the damping constant

b) inverse of the damping constant

c) twice the damping constant

d) half of the damping constant

Answer: b

Explanation: The time constant of a system is inverse of the damping constant. It is defined so and hence the rest of the options are incorrect.

11. If the natural frequency of a system increases, the rise time ________

a) Increases

b) Decreases

c) Doubles

d) Halves

Answer: b

Explanation: The rise time of a system is inversely proportional to the natural frequency of a system. Hence, if it increases, the rise time decreases.

12. The settling time is a measure of _________

a) The speed of reaching stead state

b) The speed of reaching maximum overshoot

c) The speed of reaching second overshoot

d) Nothing

Answer: a

Explanation: The settling time is a measure of the time required by the system to reach approximately 5% of it’s steady state value. Hence, it is a measure of how fast the system reaches it’s steady state value.

13. If the poles of a system transfer function are equal and imaginary, the system is ________

a) Undamped

b) Critically damped

c) Overdamped

d) Negatively damped

Answer: a

Explanation: Since the poles are equal and imaginary, the damping factor is 0 and hence the damping ratio is 0. Thus, the system is absolutely undamped and option Undamped is correct only.

14. For negative damping, the system is unstable.

a) True

b) False

Answer: a

Explanation: Negative damping implies that the response of the system grows in magnitude and it is unbounded in time. Hence, the system output is unstable and the system is also unstable.

15. An undamped system is stable.

a) True

b) False

Answer: b

Explanation: An undamped system is marginally stable or marginally unstable- it cannot be defined as stable. This is because it results in a response which is sustained by oscillatory in nature. Hence, the statement is false.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Impulse Response – 1”.


1. What is the impulse response of a system whose transfer function is that of ramp function delayed by 7 units in time?

a) r

b) r

c) r

d) Cannot be determined

Answer: a

Explanation: The impulse response is simply the inverse laplace transform of the transfer function. According to the given nature of the transfer function, the impulse response is then given by option r only.

2. What is the impulse response of a system whose transfer function is that of pulse function?

matlab-questions-answers-impulse-response-1-q2

a) u+u

b) u-u

c) u-u

d) u-u

Answer: c

Explanation: The inverse laplace transform of the transfer function gives the impulse response of a system. Now, the pulse shown in the above figure exists from t=0 to t=4 in time. The correct representation of the pulse is given by option u-u only.

3. What is the impulse response till t=16 unit in time of a system whose transfer function is that of the following?

matlab-questions-answers-impulse-response-1-q3

a) 3 ⁄ 4 *r + 3 ⁄ 4 *r+u

b) 3 ⁄ 4 *r – 3 ⁄ 4 *r-u

c) 3 ⁄ 4 *r – 3 ⁄ 4 *r-u

d) 3 ⁄ 4 *r – 3 ⁄ 4 *r-u

Answer: c

Explanation: The correct representation of the signal shown in the graph is 3 ⁄ 4 *r – 3 ⁄ 4 *r-u. This is because the ramp function, starting from t=4 units in time, has a slope of 3 ⁄ 4 and it’s shown to end at t=16. So, there it faces a slope change to 0, so the 2 nd term happens and finally, the amplitude becomes 0 which is why, the 3 rd term happens.

4. What is the impulse response of the system whose transfer function is that of a pulse which generates from the following code?


plot(0:12,[zeros(1,4),ones(1,5),zeros(1,4)])

a) u+u

b) u-u

c) u-u

d) u-u

Answer: d

Explanation: The pulse generated due to the following code, starts from t=4 and ends at t=9. The correct representation is only given by option d. Now, the impulse response is the inverse laplace transform of the system.

5. The following figure shows a set of impulse responses. Identify which system provides the greatest delay.

matlab-questions-answers-impulse-response-1-q5

a) Blue

b) Red

c) Delay

d) Purple

Answer: d

Explanation: The impulse response, represented by the purple color, suggests that the exponential factor which result in the delay of the system is higher.

6. The following figure shows a set of impulse responses. Identify which system provides the least delay.

matlab-questions-answers-impulse-response-1-q5

a) Blue

b) Red

c) Delay

d) Purple

Answer: a

Explanation: The impulse response, represented by the purple color, suggests that the exponential factor which result in the delay of the system is least. Hence, Delay is correct only.

7. Which response has the highest amplitude of step function?

matlab-questions-answers-impulse-response-1-q7

a) Yellow

b) Red

c) Blue

d) Data inadequate

Answer: a

Explanation: The impulse response is a decreasing exponential curve. This means that the amplitude of the step function will be at t=0. Hence, the correct option is a. After t=0, the response decreases exponentially which is observed by taking the inverse laplace transform of the transfer function of the system.

8. Which response has the least amplitude in the transfer function?

matlab-questions-answers-impulse-response-1-q7

a) Yellow

b) Red

c) Blue

d) Data inadequate

Answer: c

Explanation: : The impulse response is a decreasing exponential curve. This means that the amplitude of the step function will be at t=0. Hence, the correct option is yellow. After t=0, the response decreases exponentially which is observed by taking the inverse laplace transform of the transfer function of the system.

9. The o/p of the following two code snippets are ___


i.  impulse(1,[ 6 3])

ii. impulse(1/6,[ 1 .5])

a) Same graphs

b) Different grpahs

c) Amplitude of graph i>ii

d) Amplitude of graph i<ii

Answer: a

Explanation: The vector having zeros in the 1 st code snippet contains the co-efficients of the polynomial 6s+3=1/6. Hence, we find that the transfer function represented in the 2 nd code snippet is similar to the 1st code snippet. Hence, the above two systems are same and yield the same graphs.

10. Fill the half-filled code snippet which generates the following curve:

matlab-questions-answers-impulse-response-1-q10

_______Missing open brace for subscript

a) impulse, 0, 0

b) impulse, 0

c) impulse, 0 1

d) impulse, 1, 0

Answer: a

Explanation: The graph has generated a simple ramp function with slope=1. So, the impulse response is that of a ramp function. The laplace transform of ramp function is 1/s 2 . Hence, the correct option is a. Note that the command to be used is impulse only.

11. Fill the half-filled code snippet to get the following graph:

matlab-questions-answers-impulse-response-1-q11

impulse;

____;

impulse;

impulse;

impulse;

a) 2, hold, 3,4,5

b) 9, hold, 4,5,2

c) 5, hold, 4,3,2

d) Cannot be determined

Answer: a

Explanation: The above code shows that after each impulse command, the amplitude of the exponential decreases faster- besides this, it reveals that the order of the input transfer function is 1 so the transfer function is a step signal. Since we’ve plotted the impulse response, we observe that the transfer function is of the form  and if |a| increases, the response decreases faster. Hence, the only plausible option is a. The hold command should be used to plot multiple graphs on the same window.

12. Choose the correct option after observing the given graph and the code snippet carefully.

matlab-questions-answers-impulse-response-1-q11

impulse;

hold on;

impulse;

impulse;

impulse;

a) a<b

b) a>b

c) a=b

d) Cannot be determined

Answer: a

Explanation: After successive commands, the responses decreases at a faster rate. This means that the vector containing poles, given as an input to the impulse command, should have the missing elements increasing because the value of that element signifies the speed of exponential change. Hence, a should be less than b since the output due to b decreases faster as compared to that of a.

13. How does the pole of the transfer function change?

matlab-questions-answers-impulse-response-1-q13

a) Goes nearer to the origin for the green curve than the red curve

b) Goes further from the origin for the red curve than the blue curve

c) Goes nearer to the origin for the blue curve than the red curve

d) Goes nearer to the origin for the red curve than the blue curve

Answer: d

Explanation: As the impulse response suggests that each response is sinusoidal, the frequency of the sinusoid will be the value of the pole in the s-plane. If the frequency increases, the pole goes further from the curve- the output frequency increases. Hence, the plausible option is d since the frequency increases or the pole nearer to the origin from the green to the red and away form the origin from the origin from red to green.

14. Which response would provide a higher stability?

a) A step signal

b) A ramp signal

c) A sinusoidal

d) 1/

Answer: d

Explanation: All the first three options are unstable since their ROC doesn’t include the imaginary axis. For option 1/, the pole lies in the left half of s-plane and the R.O.C. includes the imaginary axis.

15. The poles of the transfer function of a sinusoidal system can represent the frequency of the impulse response of the sinusoidal system.

a) True

b) False

Answer: a

Explanation: The lapalce transform of the sinusoid represents the frequency of the signal as a pole. Since the response is sinusoidal, the transfer function is the laplace transform of the impulse response which contains the frequency as the pole of the sinusoidal system.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Impulse Response – 2”.


1. The impulse response does not take account of the transient response of the system.

a) True

b) False

Answer: b

Explanation: Since the output of a system depends on int’s initial conditions, the laplace transform of the output would depend on the transient conditions. Hence, the impulse response of the system does take account of the transient response of the system.

2. The impulse response of a parabola _________

a) will have 3 poles in the s-plane

b) will have 2 poles in the s-plane

c) will have 4 poles in the s-plane

d) will have no poles in the s-plane

Answer: a

Explanation: The transfer function of a system, whose impulse response is a parabola, will have three roots which will satisfy the characteristic equation. Hence, only option will have 3 poles in the s-plane is correct.

3. The impulse response of a sinusoid ________

a) will have 2 poles in the s-plane

b) will have 3 poles in the s-plane

c) will have 1 pole frequency in the s-plane

d) will have only 1 conjugate pole in the s-plane

Answer: a

Explanation: The transfer function of the system, whose impulse response is a sinusoid, will have 2 roots which satisfy the characteristic equation. Hence, there will be two poles which are complex conjugate to each other.

4. The step response of the impulse response of a ramp function will be ________

a) a parabolic function

b) an exponential function

c) a sinusoidal function

d) a sinc function

Answer: a

Explanation: The step response of a system can be thought in the Laplace domain as multiplication with 1/s. Now, the impulse response of ramp function is the ramp function itself while the step response of ramp function results in a parabola.

5. In MATLAB, the impulse response of the step response of a system is ___ to the step response of the impulse response of the system.

a) Equal

b) Not Equal

c) Greater

d) Lesser

Answer: a

Explanation: The distributive property of convolution suggests that the A*=*C. Thus only option Equal is correct.

6. The impulse response of the transfer function 1 is ________

a) an impulse function

b) a step function

c) a pulse function

d) cannot be determined

Answer: a

Explanation: The laplace transform of only the impulse function is 1. Hence, the inverse laplace transform.

7. What is the output of the following code?


>>p=ilaplace(1);

>>laplace(p)

a) 1

b) Impulse function

c) Error

d) Cannot be determined

Answer: c

Explanation: The ilaplace command doesn’t take double as an input. This would lead to an error and the correct option is Error.

8. What is the output of the following code?


>>p=ilaplace(s/s);

>>laplace(p)

a) dirac

b) dirac[1,t]

c) dirac{1,t}

d) Cannot be determined

Answer: a

Explanation: The ilaplace command observes that the input is actually 1. The inverse laplace transform of 1 is the impulse function which is represented as dirac in MATLAB.

9. What is the output of the following code?


>>t=(0:17);

>>o=dirac(t)==Inf;

>>q=o*1;

>>conv(q,t)

a) t followed with 17 zeros

b) t followed with 18 zeros

c) 1

d) Error

Answer: a

Explanation: In the above code, we’ve actually performed the impulse response of discrete system defined by a ramp function for [0,17]. Now, the output of the code is shown below which shows that the impulse function gets shifted for the time t and the total result of the convolution will be the entire value. Notice that the length of the convolution is 2N-1=35.

Output:

10. The impulse response is the result of the transfer function of the system.

a) True

b) False

Answer: b

Explanation: The impulse response is truly due to the impulse input given to a system. If we would’ve changed the input, the output would’ve been a different and the resulting expression in laplace domain will not be called the transfer function.

11. What is the output of the following code?


>>t=(0:17);

>> p=dirac(0)==Inf;

>> q=p*1;

>> conv(q,t)

a) An impulse response of step for a time from 0:16

b) An impulse response of unit ramp function for a time from 0:17

c) An impulse response of ramp function for a time from 0:18

d) Error in 3rd line

Answer: b

Explanation: The function p exists for only t=0 and q has only 1 element in it which is 1. So, truly, we’ve derived the convolution of a system which results in a ramp function whose slope is 1 and is ranging from 0 to 17 units in time since t is defined as such.

Output: matlab-questions-answers-impulse-response-2-q11

12. What is the output of the following code?


>> p=dirac(0)==Inf;

>> t=(0:.001:17);

>> q=p*1;

>> conv(q,sin(2*pi*t));

>> plot(t,ans)

a) A sinusoid of a frequency 1Hz

b) A sinusoid of a frequency of 17 Hz

c) A sinusoid of a frequency of .001 Hz

d) Error

Answer: a

Explanation: We’re only computing the impulse response of a system which behaves as a sinusoid on the input. The frequency of the system is 1 Hz as seen from the description. The output, shown below, contains 17 cycles.

Output: matlab-questions-answers-impulse-response-2-q12


13. What is the slope of the ramp function?

matlab-questions-answers-impulse-response-2-q13

a) 3

b) 2

c) 1

d) 6

Answer: a

Explanation: The transfer function window shows that it holds the z-transform of a ramp function. But we observe from the graph that the output changes with a step of 3. Hence, the slope of the ramp function is 3 since we are plotting the impulse response of the system.

14. What is the output at the scope?

matlab-questions-answers-impulse-response-2-q14

a) matlab-questions-answers-impulse-response-2-q14a

b) matlab-questions-answers-impulse-response-2-q14b

c) matlab-questions-answers-impulse-response-2-q14c

d) matlab-questions-answers-impulse-response-2-q14d

Answer: a

Explanation: The transfer function represents an exponentially decaying step function.Graph shows a ramp function which doesn’t have a transfer function depicted in the above figure.

15. What does the following relate to?

matlab-questions-answers-impulse-response-2-q15

a) Step response implies integrating the transfer function

b) Impulse response shows the delay in the above block diagram

c) Nothing is observed

d) The integration of impulse is a ramp function

Answer: a

Explanation: The above block diagram depicts that the impulse response of the integrator is a step function. This means that an integrator can be viewed as performing convolution of a step function and the input. Now if we imagine a system which has the same transfer function as the lapalce transform of the previous input, and we give a step input to it- it will perform convolution of the step function an the system transfer function. Thus we find that the result, due to associative property of convolution, is same and we can represent that the step response of system truly implies integrating the transfer function of the system in the output.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Operations on Signals – 1”.


1. What is the following graph if u denotes step function?

matlab-questions-answers-operations-signals-1-q1

a) u

b) u-u

c) u

d) u

Answer: b

Explanation: The unit step signal extends from 0 to infinity. When we plot it in MATLAB, we bound it to a certain point in time. In this case, we have bounded it to 1000 units in time. Hence, option u-u is correct. Option a, c and d mean the same thing but it’s not possible to represent the unit step function graphically.

2. What is the following graph if u denotes step function and r denotes ramp function?

matlab-questions-answers-operations-signals-1-q2

a) r

b) r-r-u

c) r-r

d) r-u

Answer: b

Explanation: A ramp function extends upto infinity. But here, the graph ends a 50 units in time. So, the function has a slope change at t=50 and the new slope is 0. But the function value is 0 fo r t>50 so we need to subtract the function, resulting at t=50, from a unit step function starting from t=50. Hence, the correct solution is option c only.

3. What does the following code generate?


p=ones(1,90);

t=(0:1:89);

plot(t,p);

a) A graph of a unit step function

b) A graph of a pulse function

c) A graph of a triangular pulse function

d) An impulse function

Answer: b

Explanation: The unit step function extends upto infinity and it’s not possible to represent it graphically. The above code plots a pulse function, of amplitude 1 which extends upto 89 units in time and is represented by u-u. It doesn’t generate an impulse or a triangular pulse function.

4. What is the following graph, if del represents the impulse function?

matlab-questions-answers-operations-signals-1-q4

a) del

b) del

c) del

d) del

Answer: b

Explanation: The above graph shows the impulse function at t=+100. This means that the function has been delayed by 100 units of time. Hence, the correct option is del.

5. The convolution of [1 2 1] and [1 2 1] will have the highest amplitude at t= _________

a) 3 units

b) 0 units

c) 1 unit

d) 2 units

Answer: d

Explanation: If we observe the process of graphical convolution, we find that since, the given two signals are equal to each other, the maximum amplitude of the signal generating due to convolution will be midway between the total length of the resultant signal. This is due to the fact that at that instant, one signal lies on top of another. Now the total length of the convolved signal is 5 units and the middle point is t=2. Hence, the correct option is t=2 units.

6. What is the output of the following code?


a=[1 2 3];

b=2;

a.\b;

a) .5 1 1.5

b) 2 1 .67

c) Error

d) Cannot be determined

Answer: b

Explanation: a.\b signifies a divides b so b is divided by the elements of vector a. Hence, option b is correct. The answer would’ve been .5 1 1.5 is it was a./b.

7. What is the output of the following code?


a=[1 2 3];

b=2;

conv(a,b)

a) 2 4 6

b) 1 2 3

c) 0 0 0

d) 2 3 1

Answer: a

Explanation: The process of graphical convolution will yield that the signal b only gets multiplied with an at the instants where a exists i.e at 1,2 and 3 units in time. Hence, the correct option is 2 4 6 only.

8. What is the output of the following code?


T=0:1:9;

stem(T);

a) A ramp function

b) r[n]-r[n-9]-9u[n-9]

c) r[n]-r[n-9]

d) Error

Answer: b

Explanation: Since the ramp function extends upto infinity, it cannot be represented graphically. The above code plots the ramp function from 0 to 9 units in time but the signal is represented algebraically by option r[n]-r[n-9]-9u[n-9] only. At the instant n=9, the slope of the ramp function becomes 0 so the slop changes twice i.e. first r[n] gets reduced to a step function when r[n-9] gets subtracted from it. Then we simply subtract a step function of amplitude 9 from it to get the final function.

9. What is the output of the following code?


Y=rectpulse(1,9);

t=0:1:8;

plot(t,y);

a) A rectangular pulse extending from 0 to 8 units in time

b) A rectangular pulse with increasing amplitude

c) Error

d) Cannot be determined

Answer: c

Explanation: The rectpulse command returns a column vector. But t is a row vector. So, the plot command will create an error. This is why, we need to take the transpose of the y vector and put it in the plot command.

10. What is the output of the following code?


Y=rectpulse(1,9);

p=y’;

t=0:1:9;

plot(t,p);

a) u-u

b) u till 9 units in time

c) Error

d) Cannot be determined

Answer: b

Explanation: The length of p is 9 but that of t is 10. This will result in an error in the plot command. The t vector should be from 0 to 8 or we can have rectpulse. If we want u-u, the latter is to be chosen. But here, the plot command will give an error.

This set of MATLAB Question Paper focuses on “Operations on Signals – 2”.


1. What is the output of the following code?


plot([-5:1:5],tripuls([-4:1:4])

a) Error

b) Generates a triangular pulse signal

c) Generates a sawtooth signal

d) Cannot be determined

Answer: a

Explanation: The length of the first vector given as an input to the plot command is not equal to the length of the second vector given as an input. Hence, the above code will result in an error. If the first vector was ranging from [-4:1:4], the output would’ve been Generates a triangular pulse signal only.

2. What is the output of the following code?


b={1 2 3};

c={ 1 2 3}

b+c

a) Error

b) { 2 4 6 }

c) { 1 2 3 }

d) Cannot be determined

Answer: a

Explanation: Mathematical operators like ‘+’, ‘-‘ do not work on cellular arrays. Hence, the above code will lead to an error in MATLAB.

3. What is the output of the following code?


t=[0:1:2];

plot(t,p);

hold;

plot(-t,p);

a) A mirror image of ramp function from 0 to 2 units in time

b) A ramp function from 0 to 2 units in time and it’s a mirror image in the same window

c) A ramp function from 0 to 2 units in time

d) Error

Answer: b

Explanation: Since we have used the hold command, we can now plot multiple graphs in the same window. The 1 st plot command generates a ramp function from 0 to 2 units in time while the 2 nd ramp function generates its mirror image in the same window. There is no error in the above code.

4. Discrete time convolution is not possible in MATLAB.

a) True

b) False

Answer: b

Explanation: We need to define the signal in terms of vectors and then we can give them as inputs to the conv command. This will result in the discrete time convolution.

5. plot]’) and plot) will generate the same graph.

a) True

b) False

Answer: a

Explanation: ‘rectpulse’ generates a column vector of 9 1’s. Since we have transposed it, the resultant is a row vector of 9 1s. ‘ones’ also generates 9 1’s as a row vector. Thus, the above codes will result in the same graph.

6. If x=0 for t<5 = A for t>=5, the signal is ___________

a) Causal

b) Symmetric

c) Linear, Time Invariant and Causal

d) Cannot be determined

Answer: a

Explanation: The signal given to us is delayed by 5 units in time. If we advance the signal by 5 units, the signal amplitude is 0 for t<0 but A for t>=0. Hence, the signal will be causal.

7. What is the output of the following code?


>>p=[zeros(1,5),ones(1,6)];

>> t=0:1:10;

>> plot(t,p);

a) r-r-u

b) r-u-u

c) r-u-r

d) r-r-r

Answer: a

Explanation: The signal changes from 0 to 1 from t=5 to t=6 seconds. This indicates a ramp function starting from t=5 seconds. But again it remains constant till t=10 so it signifies that the same signal is subtracted by a ramp function at t=6 seconds. Finally the signal ends at t=10 seconds so a unit step signal gets subtracted from the previous signal at t=10 seconds.

8. What is the output of the following code?


[l,m]=deconv([4 6 8],[2 3 4])

a) l=2,m=0

b) m=2,l=0

c) l=m=2

d) Error

Answer: a

Explanation: The deconv command is used for polynomial division. Since it will first return a quotient, l=2. It will next return the remainder which is 0 in this case and hence, m=0.

9. What is the output of the following code?


stem([0:1:19],[zeros(1,5) [rectpulse(1,5)] zeros(1,5) 2*[rectpulse(1,5)]])

a) Error in the input of the y axis

b) A function whose step size increases to 1 at t=5 and to 2 at t=15

c) A function whose step size increases to 1 at t=4 and to 2 at t=14

d) Syntactical Error

Answer: a

Explanation: The rectpulse command generates a column vector so it cannot be concatenated with row vectors ie with zeros. If we had taken the transpose of the vectors generated due to the rectpulse command. It leads to an error.

10. What is the output of the following code?


a=[zeros(1,4) [rectpulse(1,5)]’ zeros(1,6) 2*[rectpulse(1,9)]’];

stem([0:1:22],a];

a) Error in the input of the y axis

b) A function whose step size increases to 1 at t=5 and to 2 at t=15

c) A function whose step size increases to 1 at t=4 and to 2 at t=14

d) Error in the input of the x axis

Answer: d

Explanation: The length of the signal to be plotted, which is given as the y axis, is 24 while the length of the x axis is 23. This leads to an error since both the vectors has to be of same length.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Convolution – 1”.


1. The unit step response of an L.T.I. system is the convolution of a step signal and it’s ________

a) Impulse response

b) Ramp response

c) Parabolic response

d) Time response

Answer: a

Explanation: The response of an L.T.I. system is given by the convolution of an input and the impulse response of the system. Hence, for the unit step response of an L.T.I. system- the input is a unit step function while the convolution will be done with the impulse response. Hence, Impulse response is correct.

2. What is the output of the following code?


conv([1 2],[3 4])

a) [3 10 8]

b) [8 10 3]

c) [3 8]

d) [4 6]

Answer: a

Explanation: The convolution of two discrete signals can be thought of as simple multiplication of the polynomials which can represent those discrete signals. However, the polynomials are represented by their coefficients with the order increasing from left to right. Hence, the above code represents the convolution of  and  and by multiplying them we get [3 10 8] as the correct answer. Note that the answer would be represented by the aforementioned order.

3. What is the working of the conv2 command?

a) 2-d convolution

b) 1-d convolution

c) 3-d convolution

d) n-d convolution

Answer: a

Explanation: The conv2 command is defined in MATLAB to perform 2d convolution. Hence, only 2-d convolution is correct. This type of convolution is essential in image processing and video processing.

4. What is the output of the following code?


conv([1;3],[1;3])

a) A column vector of 1 6 9

b) A row vector of 9 6 1

c) A row vector of 1 6 9

d) A column vector of 9 6 1

Answer: a

Explanation:

The vectors are 

1 1  Take anyone and place it horizontally land flip it. 

3 3

1 3} 1  and then {3 1} 1 

3                3

Next, shift the left matrix one step in the right and the overlapping elements are to be multiplied and added. The first operation will result in 1. 

Next, invert the left matrix vertically as {3 1 

   1} 3

and multiply and add the overlapping elements.

Finally, invert the matrix horizontally as 1

   3 {3  1}. 

Multiply the overlapping element and finally we get 1 6 9 as a column vector.

5. What is the output of the following code?


conv(3,9)

a) 27

b) 3

c) 9

d) Error

Answer: a

Explanation: Since the conv command is really multiplying two signals, the above code result is 27 only. The inputs represent two polynomials which have no variable i.e. they are only constants.

6. What is the output of the following code?


conv[1 2]

a) Error in input

b) Error in []

c) 2

d) 0

Answer: b

Explanation: The first error MATLAB notices is that the input to the conv command is given within [] but not  and this is the error it’ll return. The next error is the fact that there is no ‘ , ‘ between 1 and 2 so the conv command doesn’t understand the input.

7. What is the output of the following code?


>>p=conv([ones(1,100)],[ones(1,100)]);

>>x=[1:1:199];

>> plot(x,p)

a) A triangular pulse

b) A step pulse

c) A sinusoid

d) Error

Answer: a

Explanation: The convolution of two rectangular pulses will result in a triangular pulse. The input to the conv(0 command are two rectangular pulses. Hence, triangular pulse is correct.

8. What is the length of the output?


p=conv([ones(1,150)],[ones(1,150)]);

a) 299

b) 298

c) 300

d) Error

Answer: a

Explanation: The length of the output due to convolution of two discrete signals is sum of length of each signal-1. Since the length of the input vectors is 150 each, the resultant signal would have a length of 150+150-1=299 and the correct option is 299 only.

9. What is the dimension of the output?


conv([1;2],[1;2])

a) 1*3

b) 1*4

c) 1*2

d) 2*2

Answer: a

Explanation: The dimension of the output is sum of the dimensions of length of each input-1. The dimension of each is 1*1 so the output will have 1 row but the length of columns is 2+2-1 which is equal to 3. Hence, option 1*3 is correct only.

10. What is the output of the following code?


conv([1],[2;3])

a) A column vector of 2 and 3

b) A column vector of 3 and 2

c) A row vector of 3 and 2

d) A row vector of 2 and 3

Answer: a

Explanation: The column vector of 2 and 3 is getting convolved with 1 which is a mere constant and not a vector. Hence, the output will be the same as the vector itself.

11. What is the output of the following code?


conv({1 2},{3 4})

a) Error

b) 6 8

c) 3 8

d) 3 10 8

Answer: a

Explanation: The conv command doesn’t take cellular arrays as input and this leads to an error. The output would’ve been option 3 10 8 if the vectors, given as input, were within [].

12. What is the shape output of the following code?


p=conv([ones(1,100)],[ones(1,50)])

a) A trapezoid

b) A rectangular pulse

c) A triangular pulse

d) Error

Answer: a

Explanation: An intuitive method to observe the shape of the output can be derived from the graphical convolution method. We observe that there are two pulses of unequal length. As the second vector starts overlapping on the first vector, the output increases. After it overlaps entirely on the first vector, the output would stay constant until the vector starts coming out and the output decreases linearly. Hence, the correct answer is a trapezoid.

13. What is the peak value of the output graph from the following code?


>>q=conv([1 2],[2 1]);

>> plot([0 1 2],q)

a) 5

b) 4

c) 1

d) Error

Answer: a

Explanation: The peak value of the graph will be the peak value of the output resulting due to convolution of the two signals which is 5. Hence, the correct option is 5.

14. The output of p=conv],[ones]) and p=conv],[ones]) are same.

a) True

b) False

Answer: a

Explanation: The associative property of convolution suggests that convolving a and b is same as convolving b and a. Hence, the above statement is true.

15. The signal get shifted by 1 units in time due to the following code: conv.

a) True

b) False

Answer: a

Explanation: The 2 nd row vector, in the input, acts like an impulse function delayed by 1 unit in time and exists only at t=1 unit in time. Thus, the above statement is true.

This set of MATLAB Multiple Choice Questions & Answers  focuses on ” Convolution – 2″.


1. After what instant in time will the signal output become zero?


p=conv([ones(1,100)],[ones(1,50),zeros(1,50)]);

a) 150

b) 149

c) 151

d) Error

Answer: b

Explanation: The graphical convolution gives an intuitive method to realize such cases. We observe that the second vector completely overlaps the first vector at an instant of 100 units in time. Now since we’ve flipped the second vector, we observe that the pulse of ones leaves the first vector at the instant of 149 units in time and we’re left with zeros. From here on, the output becomes 0 and hence, the correct option is 149.

2. For a causal L.T.I. system, the impulse response is 0 for _________

a) t<0

b) t=0

c) t>0

d) Always

Answer: a

Explanation: Since the system is causal, the impulse response won’t exist for t<0. This is because the output of the system should not depend on future inputs. Thus only option t<0 is correct.

3. The convolution of a discrete signal with itself is _________

a) Squaring the signal

b) Doubling the signal

c) Adding two signals

d) is not possible

Answer: a

Explanation: This is proved by the fact that since discrete signals can be thought of as a one variable polynomial with the coefficients, along with the order, representing the amplitude, at an instant equal to the order of the variable, of the signal- they are simply multiplied during convolution.

4. The convolution of a function with an impulse function delayed to an instant 3 in time results in ____________

a) An advance in the function by 3 units in time

b) The function itself

c) A delay in the function by 3 units in time

d) Cannot be determined

Answer: c

Explanation: The convolution of an impulse function with a function results in the function itself. But if the impulse function is delayed, the output will also get delayed by an equal amount. This is because

∫ ∞ -∞ f.δdk=f.

5. What is the output of the following code?


a=con([1 2],[1 2]);

b=cconv([1 2],[1 2]);

a) a=b

b) a<b

c) a>b

d) a!=b

Answer: a

Explanation: Circular and linear convolution produce the same equivalent results in MATLAB and hence the correct option is a=b. This can also be checked from the tabular method for linear and circular convolution.

6. A continuous signal can be represented as the product of an impulse function and the signal itself.

a) True

b) False

Answer: a

Explanation: The continuous signal can be represented as an integral of impulses. This representation buries it down to the form of convolution of two signal where one signal is the impulse function while the other is the continuous signal. Hence, the above statement is true.

7. What is the output of the following code?


cconv([1 2],[0 1 0])

a) [0 1 2 0]

b) [1 2 0 0]

c) [1 2 0 0]

d) [0 0 1 2]

Answer: a

Explanation: The signal is getting circularly convolved with a n impulse function which is delayed by 1 unit in time. Hence, the output of the above code will be the original function which gets delayed by 1 unit in time.

8. What is the Scope value if the signal generator has a frequency of 2 Hz only?

matlab-questions-and-answers-convolution-2-q8

a) An attenuated signal of same frequency

b) The entire signal at the same frequency

c) The entire signal at reduced frequency

d) An attenuated signal at reduced frequency

Answer: a

Explanation: The above transfer function is that of a high pass filter. The cut-off frequency for allowing signals is 3Hz but the given signal frequency is that of 2Hz only. If the frequency of the signal generator was more than 2Hz- the output would’ve been entire signal at the same frequency but for >>3Hz. Now, the convolution in time domain is multiplication in frequency domain and the output of the transfer function block is the product of the transfer function and the laplace transform of the sinusoid. It can be checked in MATLAB that the poles of the resultant function will consist of one pole at s=-2+.707i which equivalently suggest that there is a 3 db decade if the input frequency becomes less than 2hz.

9. What is the output of the following code?


P=tf([1 2],[3 4]);

Q=tf([1 2],[3 4]);

Z=P.Q;

a) Z is the response of the system whose pole is at s=-4/3

b) Z is the response of the system whose pole is at s=4/3

c) Z is the response of the system whose poles are at s=-4/3 & s=+4/3

d) Z is the response of the system whose zeros are at s=-4/3

Answer: a

Explanation: Z is the multiplication of laplace transform of two sets of two transfer functions. So if they get multiplied, the output can be the response of a system- provided one of the transfer function is the impulse response of a system while the other is just a representation of some signal. Now, this means that the poles of each function is provided in the second row vector of tf command. This means the pole can possibly be at s=-4/3 since the elements indicate increasing power of s from left to right.

10. What is the inverse laplace transform of Z from the following?


P=tf([1],[1 0 0]);

Q=tf([1],[1 0]);

Z=P.Q;

a) t 2

b) t 2 /2

c) t 3

d) Error

Answer: b

Explanation: Z is the convolution of P and Q in time domain which has been done in MATLAB by converting P and Q into the frequency domain and multiplying them. Observing that P and Q are the laplace transform of ramp and step functions respectively, Z is 1/s 3 . The inverse laplace transform of Z is simply option t 2 then.

11. What is the output of the following code?


P=tf([1 2],[3 4]);

Q=tf([1 2],[3 4]);

Z=P.Q;

ilpalace(Z)

a) Error

b) t

c) t 2

d) Cannot be determined

Answer: a

Explanation: Z is in the tf domain. So, the ilaplace command wont be able to take such variables. We need to write the entire Z as an input to the ilpalace command and then it will give the inverse lapalce transform.

12. What is the output of the following code?


conv[1 2]

a) Error in input

b) Error in []

c) 2

d) 0

Answer: b

Explanation: The first error MATLAB notices is that the input to the conv command is given within [] but not  and this is the error it’ll return. The next error is the fact that there is no ‘ , ‘ between 1 and 2 so the conv command doesn’t understand the input.

This set of MATLAB Multiple Choice Questions & Answers  focuses on “Z Transform – 1”.


1. What is the output of the following code?


ztrans(1,z)

a) 1/z-1

b) 1/z+1

c) z/

d) z/

Answer: c

Explanation: The Z-transform of 1 or unit signal is simply z/. Hence, the correct option is z/.

Output: z/

2. What is the output of the following code?


syms n;ztrans(2^n,z)

a) z/

b) z/

c) z/

d) z/

Answer: a

Explanation: If the discrete signal, x[n], gets multiplied by a^n where a is an integer, the z transform of the resultant signal becomes X(az -1 ). Hence, in the above case- the Z-transform of 2 n is actually the Z-transform of 2 n u[n]; since the Z-transform of u[n] is z/, the Z-transform of 2 n u[n] becomes z/.

Output: z/

3. What is the output of the following code?


ztrans('[1 0 1 0 1]',z)

a) [ z/, 0, z/, 0, z/]

b) [ z/, 0, z/, 0, z/]

c) [ z/, 0, z/, 0, z/]

d) [ z/, 0, z/, 0, z/]

Answer: a

Explanation: When the ztrans command gets such inputs, it calculate the Z-tranform of each element present in the vector. Hence, the correct answer should only be option [ z/, 0, z/, 0, z/] since the Z-transform of 1 or u[n] is z/.

Output: [ z/, 0, z/, 0, z/]

4. What is the output of the following code?


>>syms s;

>> ztrans('n',s)

a) s/ 2

b) ns/ 2

c) s/ 2

d) Error

Answer: a

Explanation: The Z-transform of n*xx[n] is (- z d ⁄ dz ) m * X where X is the Z transform of x[n]. Here, x[n] is unit step function whose Z-transform is z/z-1. After differentiating it and multiplying it with -z, we get s/ 2 with the variable changed to s since it has been specified in the ztrans command after the function is given as an input.

Output: s/ 2

5. What is the output of the following code?


>> ztrans('n',s)

a) s/ 2

b) ns/ 2

c) Error

d) s/ 2

Answer: c

Explanation: We have not initialized s as symbolic, MATLAB won’t be able to realize the variable s which has been given as an input to the ztrans command. Thus, this leads to an error. If s was defined symbolic, the answer would’ve been s/ 2 .

6. What is the output of the following code?


ztrans([1,2,3 4*z],z)

a) [ z/, /, /, / 2 ]

b) [ z/, /, /, / 2 ]

c) [ z/, /, /, / 2 ]

d) [ z/, /, / / 2 ]

Answer: a

Explanation: The ztrans command computes the Z-transform of every element. In doing so, the output it returns are separated by commas.

Output: [ z/, /, /, / 2 ]

7. The R.O.C. of impulse function is _________

a) The entire z-plane

b) Interior to the unit circle |z|=1

c) Exterior to the unit circle |z|=1

d) Between the unit circle |z|=1 and |z|=∞

Answer: a

Explanation: The impulse function has a Z-transform equal to 1.Since it is independent of z, it exists for all values of z. Hence, the Z-transform converges for all values of z. Thus, the R.O.C. of impulse function is the entire z-plane.

8. What is the output of the following code?


ztrans(exp(2*n),z)

a) z/)

b) z/)

c) z/)

d) z/)

Answer: a

Explanation: The Z-transform of e anT *u[n] is z/(z-e nT ). exp is taken as e 2n u[n] whose Z-transform is given by option z/).

Output: z/)

9. The bilateral Z-transform ranges from ____________

a) -∞ to ∞

b) 0 to ∞

c) -∞ to 0

d) Does not exist

Answer: a

Explanation: Unilateral Z-Transform ranges are provided in 0 to ∞ and -∞ to 0. For Bilateral Z-transform the signal can be defined in the range given in option -∞ to ∞.

10. The R.O.C. of a unit step function is __________

a) |z|>|1|

b) Entire z plane except z=0

c) Entire z plane except z=∞

d) Does not exist

Answer: a

Explanation: The unit step function is a causal infinite duration signal. The R.O.C. of a n u[n] is |z|>|a|. For a unit step function, a=1 and thus the R.O.C. is given by option only.

11. What is the relationship b/n laplace transform and z-transform of a function?

a) Impulse invariant transformation

b) z=e -sT

c) s=jw

d) s=σ

Answer: a

Explanation: The Z-transform of a signal at z=e sT yields the Laplace transform of the signal. This method of transformation is called Impulse Invariant Transformation.

12. If σ<0, the point in the z plane lies __ of the circle |z|=1.

a) Interior

b) Exterior

c) On the circumference

d) Nowhere near

Answer: a

Explanation: For σ<0, |z| is less than 1. Hence, the point lies interior to the circle |z|=1.

13. What is the T in the relation z=e sT ?

a) Sampling Period

b) Time Period

c) Normal Period

d) Average Period

Answer: a

Explanation: This equation is used to transform the signal from Laplacian domain to z domain. Here, T refers to the sampling period since the entire signal needs to be sampled at a period of T to be expressed in the z-domain.

14. The Z-transform is only for discrete signals.

a) True

b) False

Answer: a

Explanation: The signal needs to be a sampled sequence so that it can be represented in terms of the complex frequency z. Hence, the above statement is true.

15. The Z-transform doesn’t follow the linearity principle.

a) True

b) False

Answer: b

Explanation: The Z-transform does follow the principles of homogeneity and superposition. Hence, the linearity principle can be applied to check if a system is linear or not in the z-domain.

This set of MATLAB Puzzles focuses on “Z Transform – 2”.


1. The unit delay operator can be thought of in the z-domain as ___________

a) Multiplication by z -1

b) Multiplication by z

c) Multiplication by z -2

d) Multiplication by z 2

Answer: a

Explanation: If a signal is delayed by one unit in time, the Z-transform of the resultant signal is the Z-transform of the original signal which gets multiplied by z -1 . Hence, the correct option is Multiplication by z -1 .

2. The convolution of a signal in time domain can be viewed as __________

a) Multiplication in z-domain

b) Squaring in z-domain

c) Doubling the signal in z-domain

d) Convolution in z-domain

Answer: a

Explanation: This is observed from the fact that a signal can be represented as a summation of impulses and while we perform convolution in a time domain, we can represent the entire output in the form of z -n .

3. The impulse response of a discrete time system is the inverse Z-transform of the transfer function of the system in z-domain.

a) True

b) False

Answer: a

Explanation: The Z-transform of the impulse response of discrete time system gives the transfer function of the system in z-domain. This can also be achieved from the impulse invariance transformation. Hence, the converse should be true and the above statement is true.

4. What will be seen in the scope if the step time is 1 second in the following Simulink Model?

matlab-puzzles-q4

a) A unit step signal delayed by 2 units in time

b) u[n-3]

c) A ramp function

d) An impulse function

Answer: b

Explanation: Since the step time is 1, the input step signal is delayed by 1 unit already. Moreover, multiplying the signal by z-2 delays the signal further by 2 units.

5. What will be seen in the scope if the step time is 0 seconds in the following Simulink Model?

matlab-puzzles-q4

a) A unit step signal delayed by 2 units in time

b) u[n-3]

c) A ramp function

d) An impulse function

Answer: a

Explanation: The delay block will delay the signal by 2 units in time.

6. What will be seen in the Scope if the step time is 0 seconds in the following Simulink Model and the limit of x axis is n=10?

matlab-puzzles-q6

a) A delayed ramp function

b) r[n-1]

c) r[n-2]

d) Error

Answer: b

Explanation: The output of the transfer function has a the function r[n+1] and it gets delayed by two units in time to become r[n-1]. This is why the Display of the model shows 9 at n=10.

7. How much does the delay change, if the step time is taken as two units in time, in r, in scope 1 and 3?

matlab-puzzles-q7

a) 1 and 3

b) 2 and 3

c) 3 and 1

d) Error

Answer: a

Explanation: In scope 1, the input of the Transfer function block is u and the step response leads to multiplication in z-domain which shows that the ramp output gets advanced by 1 unit and the result of scope1 is r. After going through Delay of z-2, the output is r.

8. This is the output of scope1.

matlab-puzzles-q8

What is the transfer function1?

a) z/ 2

b) z 2 / 2

c) A parabola

d) A impulse function

Answer: a

Explanation: Since the output of scope 1 is a parabola and it has come from a system where the step response is seen at the output. Now, the step response is the convolution of a step signal with the impulse response of the system. In z domain, the step response becomes the product of the z-domain step signal and the transfer function of the system in z domain. Hence, it should be a ramp function whose transfer function is given by a. Option z 2 / 2 cannot be the answer since the graph shows the output delayed by 1 unit in time while option z 2 / 2 would’ve made the graph advance by 2 units in time.

9. The Discrete Transfer Fcn1 is using a ramp function.

matlab-puzzles-q9

a) True

b) False

Answer: a

Explanation: The three delays received by the output of the transfer function suggests that the response of the transfer function is a parabola itself. Thus the above statement is necessary for this case.

10. What will be seen in the scope?

matlab-puzzles-q10

a) A ramp function

b) A step function

c) A parabola

d) A hyperbola

Answer: a

Explanation: The transfer function is a step function and the step response of a step function is a ramp function. Hence, the output in the scope is just a ramp function.