МатематикаМоя статистика
Тест по MATLAB
100 вопросов в 10 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Векторы и матрицы, индексация, поэлементные и матричные операции, функции и анонимные функции, линейная алгебра, графики, ode45 и численные методы, ячейки и структуры, векторизация. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Basics and syntax10
What does the semicolon at the end of this statement do?
x = 5;- It suppresses the display of the result; x is still assigned the value 5
- It is required to end every statement; leaving it out causes a syntax error
- It makes x a constant that cannot be reassigned later
- It turns the rest of the line into a comment
A trailing semicolon only stops MATLAB from echoing the result in the Command Window; the assignment happens either way. Without it the statement is still valid and MATLAB simply prints x = 5. Thinking the semicolon is mandatory (as in C or Java) is the typical mistake; in long loops it is the missing semicolon that floods the screen and slows the code down.
You type this expression in the Command Window without assigning it to anything. Where is the value 7 stored?
3 + 4- In the automatic variable ans
- In a variable named result
- Nowhere; it is only printed and then discarded
- In the variable that was assigned most recently
When an expression is evaluated without an assignment, MATLAB stores its value in the special variable ans, which is overwritten by the next unassigned expression. There is no variable named result, and the last assigned variable is untouched. Relying on ans in scripts is fragile because any later unassigned expression replaces it.
What happens when this code runs?
v = [10 20 30];
v(0)- An error: array indices must be positive integers
- It returns 30, because index 0 wraps around to the last element
- It returns 10, the first element
- It returns [] (an empty array)
MATLAB arrays are indexed from 1, so v(1) is 10 and index 0 does not exist; MATLAB stops with an error about indices having to be positive integers (or logical values). Expecting 10 is the classic mistake of programmers coming from 0-based languages such as C or Python, and negative or zero indices never wrap around as they do in Python.
What is the value of ans after these three lines run?
x = 7;
x + 1;
y = 2 * x;- 14
- 7
- ans is undefined, because x + 1; was suppressed by the semicolon
- 8
x + 1; is an unassigned expression, so its value 8 goes into ans; the semicolon only hides the output, it does not stop the assignment to ans. y = 2 * x is an assignment to y and does not touch ans, so 14 is wrong. Confusing "not displayed" with "not evaluated" is the mistake behind the "ans is undefined" answer.
What is the value of z after this code?
for i = 1:3
end
z = 2 + 3*i- 2.0000 + 3.0000i
- 11
- An error, because the loop variable i no longer exists after the loop
- [5 8 11]
i (and j) are only the imaginary unit until you assign them. The loop leaves i = 3 in the workspace, so 2 + 3*i is 2 + 9 = 11. The loop variable keeps its last value after the loop, it is not deleted. To write complex numbers safely use the literals 3i or 1i (e.g. 2 + 3i), which cannot be shadowed by a variable.
Which of these lines is a comment in MATLAB?
- % compute the mean
- // compute the mean
- /* compute the mean */
- -- compute the mean
In MATLAB a comment starts with the percent sign % and runs to the end of the line; block comments use %{ and %} on lines of their own. // and /* */ come from C-like languages and -- from SQL or Lua; MATLAB treats them as code and reports a syntax error. (GNU Octave also accepts #, but that is not valid MATLAB.)
Which command removes all variables from the workspace?
- clc
- close all
- clf
- clear
clear deletes variables from the workspace (clear x removes just x). clc only clears the text in the Command Window, close all closes figure windows and clf clears the current figure. Running clc and expecting old variables to be gone is a common mistake that leaves stale values in later computations.
Which of these is a valid MATLAB variable name?
- velocity_2
- _velocity
- 2velocity
- velocity-2
Variable names must start with a letter and may contain letters, digits and underscores (up to namelengthmax = 63 characters). 2velocity starts with a digit, _velocity starts with an underscore (allowed in C or Python, but not in MATLAB), and velocity-2 would be parsed as velocity minus 2.
What is total after these two lines?
total = 1 + 2 ...
+ 3;- 6
- 3, and the second line is evaluated separately as ans = 3
- An error, because a statement cannot start with +
- An error, because ... is not valid MATLAB syntax
Three dots ... at the end of a line continue the statement on the next line, so this is total = 1 + 2 + 3 = 6. Without the dots, the first line would give total = 3 and the second line would be a separate expression +3 stored in ans. Any text after ... on the same line is ignored like a comment.
What is a after this code?
a = 5;
a(3) = 1;- An error, because index 3 exceeds the size of a scalar
- [5 1]
- 1, because a is overwritten
- [5 0 1]
A scalar is just a 1x1 array. Assigning to an index beyond the current size grows the array and fills the gap with zeros, so a becomes [5 0 1]. Only reading past the end (e.g. b = a(3) when a is a scalar) raises "index exceeds the number of array elements". This silent growth is convenient but also hides typos in index variables.
Vectors and matrices10
What does the expression 1:2:9 produce?
- [1 2 3 4 5 6 7 8 9]
- [2 4 6 8]
- [1 3 5 7]
- [1 3 5 7 9]
The colon operator is start:step:stop, so 1:2:9 starts at 1 and adds 2 while the value does not exceed 9, giving [1 3 5 7 9]. The end value is included when the step lands on it exactly, so [1 3 5 7] is wrong. Reading it as start:stop:step (as in Python's slice order) is the typical mistake.
What does size(zeros(3, 4)) return?
- [3 4]
- [4 3]
- 12
- 7
zeros(m, n) creates an m-by-n matrix, i.e. 3 rows and 4 columns, and size returns [rows columns] = [3 4]. 12 is numel (the total number of elements), and [4 3] comes from treating the first argument as the width, which is the usual mistake.
What are the values of length(A) and numel(A)?
A = ones(2, 5);- 2 and 10
- 5 and 10
- 10 and 10
- 5 and 7
numel returns the total number of elements, 2*5 = 10. length returns the size of the largest dimension, max(size(A)) = 5, not the number of rows and not the element count. Using length on matrices is a common source of bugs; use size(A, 1), size(A, 2) or numel(A) to say exactly what you mean.
What does linspace(0, 1, 4) return?
- [0 0.2500 0.5000 0.7500 1.0000]
- [0 0.2500 0.5000 0.7500]
- [0 0.3333 0.6667]
- [0 0.3333 0.6667 1.0000]
The third argument of linspace is the number of points, not the number of intervals, and both end points are included. Four points between 0 and 1 make three gaps of 1/3. Expecting a step of 0.25 (four intervals) is the classic off-by-one; that needs linspace(0, 1, 5).
What does size(B) return?
A = [1 2; 3 4];
B = cat(3, A, A);- [4 2]
- [2 4]
- [2 2 2]
- [2 2 3]
cat(dim, ...) concatenates along dimension dim. cat(1, A, A) would be [A; A] (4x2) and cat(2, A, A) would be [A, A] (2x4); cat(3, A, A) stacks the two 2x2 matrices as pages of a 3-D array, so the size is 2x2x2. The first argument is the dimension, not one of the arrays, which is why [2 2 3] is wrong.
What does eye(3) create?
- A 3x3 matrix of ones
- The 3x3 identity matrix: ones on the main diagonal, zeros elsewhere
- The row vector [1 1 1]
- A 3x3 matrix with ones on the anti-diagonal
eye(n) returns the n-by-n identity matrix I, for which A*I = A. ones(3) would be the matrix of all ones. The anti-diagonal version is fliplr(eye(3)). The name is a pun on the letter I, used for the identity matrix in mathematics.
What does zeros(3) create?
- A 3x3 matrix of zeros
- The column vector [0; 0; 0]
- The row vector [0 0 0]
- The scalar 0, repeated three times in the output
With a single argument n, zeros(n) (like ones(n), rand(n) and eye(n)) creates a square n-by-n matrix. For a 1x3 row write zeros(1, 3), for a column zeros(3, 1). Calling zeros(n) when a vector was intended creates n^2 elements, which for large n can exhaust memory.
What happens with this statement?
M = [1 2; 3 4 5];- An error, because the rows have different numbers of columns
- M is the 1x5 row vector [1 2 3 4 5]
- M is [1 2 0; 3 4 5], with the short row padded by zero
- M becomes a cell array with rows of different lengths
Inside square brackets a space or comma separates columns and a semicolon starts a new row; all rows of a matrix must have the same number of columns. The first row has 2, the second 3, so MATLAB raises a dimensions-of-arrays-being-concatenated error. There is no automatic padding, and only braces {} create cell arrays.
What does 5:1 return?
- [5 4 3 2 1]
- An empty 1x0 array
- An error, because the start is greater than the end
- 5
The default step of the colon operator is +1. Starting at 5 and counting up, the first value is already past 1, so the result is empty (1x0). To count down, the step must be given explicitly: 5:-1:1. A for loop over 5:1 therefore silently runs zero times, a typical bug in backward loops.
What does repmat([1 2], 2, 2) return?
- [1 2; 1 2]
- [1 1 2 2; 1 1 2 2]
- [2 4]
- [1 2 1 2; 1 2 1 2]
repmat(A, m, n) tiles the whole block A m times vertically and n times horizontally. The 1x2 block [1 2] tiled 2x2 gives a 2x4 matrix with the block repeated in each row. [1 1 2 2; ...] repeats each element instead (that is what repelem([1 2], 2, 2) does). In modern code implicit expansion often replaces repmat.
Indexing10
What does A(2, 3) return?
A = [1 2 3; 4 5 6];- 6
- 3
- 5
- 4
Subscript indexing is A(row, column): row 2 is [4 5 6] and its third element is 6. Swapping the order (column, row) is the typical mistake; A(3, 2) would even be an error here because A has only 2 rows.
What does v(v > 4) return?
v = [5 8 2 9];- [1 1 0 1]
- [5 8 9]
- [1 2 4]
- 3
v > 4 is the logical array [1 1 0 1]; using it as an index keeps the elements where it is true, giving [5 8 9]. [1 1 0 1] is the logical mask itself, find(v > 4) would give the positions [1 2 4], and nnz(v > 4) or sum(v > 4) would give the count 3.
What does A(3) return?
A = [1 2 3; 4 5 6];- 3
- 4
- 2
- An error: a matrix needs two subscripts
A single index is a linear index, and MATLAB stores arrays in column-major order: A(:) is [1; 4; 2; 5; 3; 6], so A(3) is 2. Answering 3 assumes row-major order (as in C or NumPy's default). Linear indexing is perfectly legal on matrices and is what find returns by default.
What is v after this code?
v = [5 8 2 9];
v(2) = [];- [5 0 2 9]
- [5 2 9 0]
- An error, because [] cannot be assigned to one element
- [5 2 9]
Assigning the empty array [] to an indexed part deletes those elements, so the vector shrinks to [5 2 9]. It does not replace the value by 0 or keep the length; to set an element to zero write v(2) = 0. Deleting elements in a loop that walks forward over the indices is a common bug, because the later elements shift left.
What does sub2ind([3 4], 2, 3) return (the linear index of row 2, column 3 in a 3x4 matrix)?
- 7
- 8
- 6
- 10
In column-major order the linear index is (col - 1) * nRows + row = (3 - 1) * 3 + 2 = 8: two full columns of 3 elements, then the second element of the third column. 7 is the row-major formula (row - 1) * nCols + col, the usual mistake when coming from C or Python.
What does v(end) return?
v = [4 7 1 9 3];- 5, the length of v
- 3
- 9, the largest element
- An error: end can only close a block such as for or if
Inside an index expression end means the last index in that dimension, here 5, so v(end) is v(5) = 3. end does not return the length itself (that would be numel(v)), and it is not the maximum (max(v) = 9). The same keyword also closes blocks, but in parentheses after an array name it is an index.
What does A(:, 2) return?
A = [1 2 3; 4 5 6];- [4 5 6], the second row
- [2 5] as a row vector
- 4, the second element in memory
- [2; 5], the second column as a column vector
The colon in the row position means "all rows", so A(:, 2) is the entire second column, returned with its column shape [2; 5]. The second row would be A(2, :). A single index A(2) is linear indexing and gives 4 because of column-major storage.
What is v after this code?
v = 1:3;
v(6) = 1;- An error: index exceeds the number of array elements
- [1 2 3 1]
- [1 2 3 0 0 1]
- [1 2 3 NaN NaN 1]
Assigning to an index past the end grows the array to that size and fills the gap with zeros: v becomes [1 2 3 0 0 1]. The element is not appended at position 4, and the gap is not filled with NaN. The "index exceeds" error only happens when reading, e.g. x = v(6) for a 3-element v.
What does A(end, end-1) return?
A = [1 2 3; 4 5 6; 7 8 9];- 8
- 6
- 9
- 7
In each subscript end means the last index of that dimension: the row end is 3 and the column end - 1 is 2, so the element is A(3, 2) = 8. 6 is A(end-1, end) with the subscripts swapped, and 9 is A(end, end).
What happens with this code?
v = [10 20 30];
idx = [1 0 1];
w = v(idx);- w is [10 30]
- w is [10 0 30]
- w is [10 10], the index 0 is skipped
- An error, because 0 is not a valid numeric index
[1 0 1] typed as numbers is a double array, so it is used as a list of positions, and position 0 does not exist. Only a logical array works as a mask: v(logical([1 0 1])) or v(v ~= 20) gives [10 30]. Comparison results are already logical, which is why masks built with relational operators work while hand-typed 0/1 vectors do not.
Element-wise vs matrix operations10
What does this expression return?
[1 2 3] .* [4 5 6]- [4 10 18]
- 32
- [5 7 9]
- An error: inner matrix dimensions must agree
.* multiplies element by element, so the result is [1*4 2*5 3*6] = [4 10 18]. 32 is the dot product, which you get with dot(a, b) or a * b'. The error message belongs to the plain * operator, which is matrix multiplication and cannot multiply two 1x3 vectors.
What happens when this expression is evaluated?
[1 2 3] * [4 5 6]- It returns 32, the dot product
- It returns [4 10 18]
- It returns a 3x3 matrix
- An error, because the inner dimensions of a 1x3 and a 1x3 matrix do not agree
* is matrix multiplication: an m-by-n matrix times an n-by-p matrix. A 1x3 times a 1x3 has inner dimensions 3 and 1, so MATLAB raises an "incorrect dimensions for matrix multiplication" error. Use .* for [4 10 18], [1 2 3] * [4 5 6]' for 32, or [1 2 3]' * [4 5 6] for the 3x3 outer product.
What does A^2 return?
A = [1 2; 3 4];- [1 4; 9 16]
- [7 10; 15 22]
- [2 4; 6 8]
- An error: use .^ for matrices
^ is the matrix power, so A^2 is A*A = [1*1+2*3 1*2+2*4; 3*1+4*3 3*2+4*4] = [7 10; 15 22]. [1 4; 9 16] is A.^2, the element-wise square. A^2 is perfectly valid for a square matrix; it only errors for non-square arrays such as row vectors. Mixing up ^ and .^ is one of the most common MATLAB bugs.
What does z' return?
z = [1+2i, 3];- [1+2i; 3]
- [1-2i, 3] (still a row vector)
- [1-2i; 3]
- An error, because ' is not defined for complex numbers
' is the complex conjugate transpose (ctranspose): it turns the row into a column and conjugates every element. The plain transpose without conjugation is .' (transpose), which would give [1+2i; 3]. Using ' when you only want to reshape complex data, e.g. FFT results, silently flips the sign of the imaginary parts.
In MATLAB R2016b or newer (and in GNU Octave), what does this expression return?
[1; 2] + [10 20 30]- An error: matrix dimensions must agree
- [11 22]
- A 1x6 row vector
- [11 21 31; 12 22 32]
Since R2016b MATLAB applies implicit expansion (Octave calls it broadcasting): a 2x1 column and a 1x3 row are both expanded to 2x3, and element (i, j) is a(i) + b(j). Older MATLAB versions raised the dimension error and needed bsxfun(@plus, ...). Implicit expansion can also hide bugs: adding a row to a column by accident silently produces a matrix instead of an error.
Why does the second line fail?
x = 0:0.5:2;
y = x^2;- Because x must be a column vector
- Because ^ is the matrix power, which needs a square matrix; element-wise squaring is x.^2
- Because 0 cannot be raised to a power
- Because squaring is only allowed inside a for loop
x is a 1x5 row vector. ^ means matrix power, x^2 = x*x, which is defined only for square matrices, so MATLAB raises an error. The element-wise operator .^ squares each element: x.^2 = [0 0.25 1 2.25 4]. The same rule applies to * vs .* and / vs ./ whenever you compute a formula on vectors.
What does size([1 2 3]') return?
- [1 3]
- 3
- [3 1]
- [3 3]
The apostrophe transposes the 1x3 row vector into a 3x1 column vector, so size returns [3 1]. The transpose changes the shape, not the number of elements, and size always returns at least two dimensions, so 3 is wrong (that is numel).
What does this expression return?
[1 2 3] * [4 5 6]'- [4 10 18]
- A 3x3 matrix
- An error: inner matrix dimensions must agree
- 32
The transpose makes the second factor a 3x1 column, so this is a 1x3 times a 3x1 matrix product: a 1x1 result 1*4 + 2*5 + 3*6 = 32, the dot product. [4 10 18] would be .* without the transpose, and the 3x3 outer product needs the opposite order, [1 2 3]' * [4 5 6].
v = [1 2 4]. Which expression returns [2 1 0.5]?
- 2 ./ v
- 2 / v
- v / 2
- v .^ 2
./ divides element by element, so 2 ./ v = [2/1 2/2 2/4] = [2 1 0.5]. 2 / v is the matrix right division (solve x*v = 2), which fails because a 1x1 and a 1x3 do not have the same number of columns. v / 2 divides each element by the scalar and gives [0.5 1 2]: dividing an array by a scalar works with /, but a scalar divided by an array needs ./.
b is a 1x3 row vector and A is a nonsingular 3x3 matrix. What does x = b / A compute?
- Each element of b divided by the corresponding element of A
- The column vector x that solves A*x = b
- An error, because / cannot divide by a matrix
- The row vector x that solves x*A = b
/ is matrix right division (mrdivide): b / A solves x*A = b and equals b * inv(A) mathematically, computed without forming the inverse. The left division A \ b solves A*x = b for a column b. Element-wise division is ./, which would also fail here because a 1x3 and a 3x3 array are not compatible sizes.
Control flow and functions10
What is s after this loop?
s = 0;
for k = 1:4
s = s + k;
end- 4
- 10
- 6
- 15
The loop runs for k = 1, 2, 3, 4 (the end value of 1:4 is included), so s = 1 + 2 + 3 + 4 = 10. 6 comes from assuming the end is excluded as in Python's range, and 15 from running one step too far. The vectorized version is simply sum(1:4).
What does f(3) return?
f = @(x) x.^2 + 1;- 10
- 7
- 16
- An error: anonymous functions must be called with feval
@(x) x.^2 + 1 creates an anonymous function handle with one input; f(3) evaluates 3^2 + 1 = 10. 16 comes from computing (3 + 1)^2, i.e. ignoring operator precedence. Function handles are called directly with parentheses; feval(f, 3) also works but is not required.
Given this function file sumprod.m, what is r after r = sumprod(2, 3)?
function [s, p] = sumprod(a, b)
s = a + b;
p = a * b;
end- 6
- [5 6]
- 5
- An error, because both outputs must be requested
When fewer outputs are requested than declared, MATLAB returns them in order and drops the rest, so r gets the first output s = 5. To get both use [s, p] = sumprod(2, 3), and to get only the second use [~, p] = sumprod(2, 3). Expecting [5 6] is a common mistake: multiple outputs are separate values, not one vector.
What is s after this loop?
s = 0;
for k = 1:10
if mod(k, 2) == 0
continue
end
s = s + k;
end- 30
- 55
- 9
- 25
continue skips the rest of the current iteration, so even k values are not added and s = 1 + 3 + 5 + 7 + 9 = 25. 30 is the sum of the even numbers (reading the condition backwards), 55 ignores continue entirely, and 9 would be the answer if continue were break-like or s were overwritten instead of accumulated.
What does this code display?
x = [3 -1 2];
if x > 0
disp('all positive')
else
disp('not all positive')
end- not all positive
- all positive
- An error, because if needs a scalar condition
- It prints a message once for each element of x
x > 0 is the array [1 0 1]. When the condition of if or while is an array, it counts as true only if it is non-empty and all elements are nonzero, so this takes the else branch. MATLAB does not loop over the elements and does not error. Write all(x > 0) or any(x > 0) explicitly to make the intent clear.
What is n after this loop?
n = 1;
while n < 50
n = n * 2;
end- 32
- 50
- 64
- 128
n doubles while the condition n < 50 holds: 1, 2, 4, 8, 16, 32 are all below 50, so 32 is doubled once more to 64, and then the test fails. A while loop checks the condition before each iteration, so the final value is the first one that fails the test, not the last one that passed (32).
Given this function file scale.m, what does scale(3) return?
function y = scale(x, k)
if nargin < 2
k = 10;
end
y = k * x;
end- An error: not enough input arguments
- 30
- 3
- 0, because the missing k defaults to 0
nargin is the number of inputs actually passed. scale(3) passes one argument, so the if branch sets the default k = 10 and the result is 30. MATLAB allows calling a function with fewer inputs than declared; the "not enough input arguments" error only occurs if the code uses a missing input without setting it first. Missing inputs never default to 0.
In MATLAB, the file area.m begins with the line below. How is this function called from the command line?
function r = circleArea(d)- area(2)
- circleArea(2)
- Either area(2) or circleArea(2)
- It cannot be called; MATLAB refuses to load the file
For the main function of a file, MATLAB uses the file name, not the name written after function. The editor warns about the mismatch, but the call is area(2), and circleArea is unknown outside the file. Renaming the function line without renaming the file is a common source of "Undefined function" errors, so keep them identical.
What does f(3) return at the end of this code?
a = 2;
f = @(x) a * x;
a = 10;
f(3)- 30
- 6
- An error, because a is not an input of f
- [6 30]
An anonymous function captures the values of the variables it uses at the moment the handle is created. f stores a = 2, so later changes to a in the workspace do not affect it and f(3) = 6. Expecting 30 is the typical mistake; to use the new value, recreate the handle after changing a or make a an explicit input: f = @(x, a) a * x.
What is n after this loop?
n = 0;
for c = [1 2 3; 4 5 6]
n = n + 1;
end- 6
- 2
- 3
- 1
A for loop iterates over the columns of the array after the equals sign. The 2x3 matrix has 3 columns, so the body runs 3 times and c is [1; 4], then [2; 5], then [3; 6]. Expecting 6 iterations (one per element) is the typical mistake; to loop over all elements use for c = A(:)'.
Linear algebra10
What is the recommended way to solve the linear system A*x = b for a square, nonsingular A and column vector b?
- x = b \ A
- x = A / b
- x = b / A
- x = A \ b
The backslash operator (mldivide) solves A*x = b directly with a suitable factorization (LU, Cholesky, QR...) chosen from the structure of A. The order matters: A \ b means "A divides b from the left". b / A solves x*A = b, a different problem, and with a column vector b its dimensions do not even match.
What does det([1 2; 3 4]) return?
- 2
- 10
- -2
- 24
For a 2x2 matrix det = a*d - b*c = 1*4 - 2*3 = -2. 2 drops the sign, 10 adds the products instead of subtracting, and 24 multiplies all elements. In numerical work det is a poor test of singularity; use rank or cond instead.
What does rank(A) return?
A = [1 2 3; 2 4 6; 1 0 1];- 3
- 2
- 1
- 0
The second row is exactly twice the first, so only two rows are linearly independent: rank is 2. Answering 3 assumes every square matrix has full rank just because it is 3x3; that is only true for nonsingular matrices. MATLAB computes rank from the singular values (counting those above a tolerance), so it is reliable even with rounding.
What does MATLAB do when it runs this code?
A = [1 2; 2 4];
x = A \ [3; 6];- It stops with an error, because a singular system has no unique solution
- It silently returns the minimum-norm solution
- It prints a warning that the matrix is singular to working precision and still returns a result that should not be trusted
- It returns an empty matrix []
A is singular (the second row is twice the first). Backslash does not throw an error for a square singular matrix: it warns "Matrix is singular to working precision" (Octave: "matrix singular to machine precision") and returns whatever the factorization produced, possibly containing Inf or NaN. Ignoring this warning is a typical mistake; for a minimum-norm least-squares answer use pinv(A)*b or lsqminnorm.
cond(A) returns about 1e12 for a matrix A. What does that tell you about x = A \ b computed in double precision?
- A is singular, so A \ b will always fail
- The determinant of A is about 1e12
- Roughly 12 of the about 16 significant decimal digits of x may be lost to rounding errors
- Solving the system will take about 1e12 times longer than for a well-conditioned matrix
The condition number bounds how much relative errors in the data (including rounding at about eps = 2.2e-16) can be amplified in the solution: relative error up to about cond(A) * eps = 1e-4, so only about 4 digits are reliable. A large condition number means ill-conditioned, not exactly singular, and it has nothing to do with the determinant or the run time. MATLAB warns "Matrix is close to singular or badly scaled" when the estimate is large.
What does norm([3 4]) return?
- 7
- 25
- 5
- 4
For a vector, norm(v) is the Euclidean 2-norm sqrt(sum(v.^2)) = sqrt(9 + 16) = 5. 7 is the 1-norm norm(v, 1) (sum of absolute values), 25 is the squared norm and 4 is the infinity norm norm(v, Inf) (the largest absolute value).
After [V, D] = eig(A) for a square matrix A, which statement is true?
- The rows of V are the eigenvectors and A*V = D*V
- The columns of V are eigenvectors, D is diagonal with the eigenvalues, and A*V = V*D
- V holds the eigenvalues and D the eigenvectors
- D is the determinant of A and V its inverse
eig with two outputs returns the eigenvectors as the columns of V and the eigenvalues on the diagonal of D, matching column by column: A*V(:, k) = D(k, k)*V(:, k), i.e. A*V = V*D. With one output, e = eig(A) returns only the eigenvalues as a column vector. Taking rows of V as eigenvectors is the usual mistake.
Why is x = A \ b preferred over x = inv(A) * b?
- Because inv only works for 2x2 matrices
- Because the results are identical and A \ b is just shorter to type
- Because A \ b solves the system with a factorization without forming the inverse, which needs fewer operations and usually gives smaller rounding errors
- Because inv(A) * b returns a row vector instead of a column vector
Computing the inverse explicitly costs more than one factorization plus substitution, and multiplying by an inverse that is itself rounded adds error, especially for ill-conditioned A. Backslash also picks a specialised solver (triangular, banded, Cholesky) based on the structure of A, and it warns about singular matrices. inv works for any nonsingular square size and returns the same shape as A \ b; the results are close but not identical.
What does x = A \ b return for this non-square system?
A = [1 0; 1 1; 1 2];
b = [1; 2; 2];
x = A \ b;- An error, because A must be square
- The exact solution of the first two equations only
- The 2x1 least-squares solution that minimizes norm(A*x - b)
- A 3x1 vector, one value per equation
For an overdetermined system (more equations than unknowns) backslash computes the least-squares solution with a QR factorization: the x that minimizes the residual norm. This is the standard way to fit a line y = c1 + c2*t to data with t = [0 1 2]. The result has one entry per unknown (columns of A), here 2, and no equation is simply dropped.
What are norm(A, 1) and norm(A, Inf)?
A = [1 -2; 3 4];- 6 and 7
- 7 and 6
- 4 and 7
- 10 and 10
The matrix 1-norm is the maximum absolute column sum: max(|1| + |3|, |-2| + |4|) = max(4, 6) = 6. The infinity norm is the maximum absolute row sum: max(|1| + |-2|, |3| + |4|) = max(3, 7) = 7. Swapping the two definitions gives 7 and 6, and forgetting the absolute values gives 4 for the column sums.
Plotting10
What does hold on do?
- It keeps the current plot so the next plot command adds to the same axes instead of replacing it
- It pauses the script until the figure window is closed
- It locks the axis limits but still replaces the existing lines
- It opens a new figure window for every following plot command
By default each plot call clears the current axes and draws anew. hold on keeps the existing graphics so several curves can be drawn on one set of axes; hold off restores the default. Forgetting hold on is why only the last curve is visible; to open a new window you call figure instead.
What does this command draw?
plot(x, y, 'r--o')- A red solid line with the letter o printed at each point
- A red dotted line with zero markers
- A red dashed line with circle markers at the data points
- A red line twice as thick as the default
The line specification combines a color (r = red), a line style (-- = dashed) and a marker (o = circle). A dotted line would be ':' and a solid line '-'. Line width is not part of the short line spec; it is set with plot(x, y, 'r--o', 'LineWidth', 2).
In a figure divided with subplot(2, 3, p), where is the axes created by subplot(2, 3, 4)?
- Row 1, column 2
- Row 2, column 2
- Nowhere: it is an error, because 4 is larger than the 3 columns
- Row 2, column 1
subplot(m, n, p) splits the figure into m rows and n columns and numbers the panes row by row: 1, 2, 3 in the first row and 4, 5, 6 in the second. So p = 4 is the first pane of the second row. Counting down the columns (column-major, as for array indexing) is the typical mistake; it would put p = 4 at row 2, column 2.
What is size(X) after this call?
[X, Y] = meshgrid(1:3, 1:2);- [3 2]
- [2 3]
- [1 3]
- [6 1]
meshgrid(x, y) returns matrices with length(y) rows and length(x) columns, so that X varies along the columns (horizontal direction) and Y along the rows, matching how surf and contour draw them. Here that is 2x3. Expecting [3 2] confuses it with ndgrid, which uses the opposite (row = first argument) convention.
A is a 3x4 matrix. What does plot(A) draw?
- Three lines, one for each row
- Four lines, one for each column, each plotted against the indices 1, 2, 3
- A single line through all 12 values in column-major order
- A 3-D surface, since A is a matrix
When plot gets a matrix it draws one line per column, with the row index 1..size(A, 1) as the x coordinate. To get one line per row, plot the transpose: plot(A'). Surfaces need surf or mesh; plot always draws 2-D lines.
Which command labels the horizontal axis of the current plot?
- title('Time (s)')
- xlabel('Time (s)')
- legend('Time (s)')
- xlim('Time (s)')
xlabel, ylabel and zlabel set the axis labels; title puts text above the axes and legend creates the key that names the plotted lines. xlim sets the numeric limits of the x axis, e.g. xlim([0 10]), and does not accept a label.
What is the main visual difference between mesh(X, Y, Z) and surf(X, Y, Z)?
- mesh needs meshgrid matrices and surf accepts only vectors
- surf draws a 2-D contour plot and mesh a 3-D surface
- There is no difference; they are aliases
- mesh draws only the colored grid lines (a wireframe), while surf also fills the faces with color
Both take the same X, Y, Z data and draw a 3-D surface. mesh shows only the edges of the grid (the faces are left unfilled), while surf fills each patch with color and draws the edges in black. Contour plots are made with contour or contourf.
What are the x coordinates of the points drawn by this code?
y = [4 1 3];
plot(y)- 0, 1, 2
- 4, 1, 3 (the values are plotted against themselves)
- 1, 2, 3
- Nothing is drawn: plot needs both x and y
With a single vector argument, plot uses the indices 1:numel(y) as the x values. Assuming 0-based x values is the typical mistake. When the samples have a real time or position axis, always pass it explicitly, e.g. plot(t, y), or the axis will be labelled with sample numbers.
You plot a circle with plot(cos(t), sin(t)) and it looks like an ellipse. What does axis equal change?
- It uses the same length for one data unit on the x and y axes, so the circle looks round
- It sets the same numeric limits for both axes, e.g. [-1 1] for x and y
- It resizes the figure window to a square
- It forces both axes to start at 0
axis equal sets the data aspect ratio to 1:1, so one unit on x has the same length on screen as one unit on y; the limits can still differ. The figure window itself is not resized. axis square, by contrast, makes the axes box square without equalizing units, which still distorts shapes when the ranges differ.
Why does the last line fail?
x = 0:0.1:1;
y = 0:0.1:2;
[X, Y] = meshgrid(x, y);
Z = X * Y;
surf(X, Y, Z)- meshgrid must be called as meshgrid(y, x)
- surf accepts only vectors, not matrices
- Z must be computed in a nested for loop
- X * Y is a matrix product of two 21x11 matrices, whose inner dimensions do not agree; Z = X .* Y is needed
X and Y are both 21x11 (rows = length(y), columns = length(x)). The function z = x*y has to be evaluated point by point with the element-wise operator .*; the matrix product * of two 21x11 matrices raises a dimension error (and when the grid is square it silently computes something meaningless). Forgetting the dot in grid formulas is the most common surf bug.
Numerical methods10
What does fzero return here?
r = fzero(@(x) cos(x) - x, 1);- 1, the starting point
- 0.5403, which is cos(1)
- About 0.7391, a point where cos(x) = x
- 0, because fzero looks for the minimum of the function
fzero finds a root of a scalar function of one variable, i.e. an x with cos(x) - x = 0, starting the search from x0 = 1; the root is about 0.7391. It does not minimize the function (that is fminbnd or fminsearch), and it does not just evaluate the function at the starting point.
What is p after this call?
p = polyfit([0 1 2], [1 3 5], 1);- [2 1] (approximately): slope 2, intercept 1
- [1 2]: intercept 1, slope 2
- [1 3 5]
- 2, only the slope
polyfit returns the coefficients in descending powers, the same order polyval expects: for degree 1 that is [slope intercept]. The data lie exactly on y = 2x + 1, so p is [2 1] up to rounding. Reading p(1) as the constant term is the typical mistake.
You want to solve dy/dt = t - y with ode45. Which function handle has the correct form?
- @(y, t) t - y
- @(t) t - y
- @(t, y) t - y
- 't - y'
ode45 always calls the function as f(t, y), time first, and expects dy/dt as a column vector. @(y, t) t - y is syntactically valid but ode45 would pass time into y and the state into t, silently solving the wrong equation (here dy/dt = y - t). @(t) t - y would capture a fixed y from the workspace (or fail), and ode45 does not accept expression strings.
Why does this call fail, and what fixes it?
q = integral(@(x) x^2, 0, 3);- integral needs an expression string: integral('x^2', 0, 3)
- The limits must be passed as one vector: integral(@(x) x^2, [0 3])
- integral only accepts named functions, not anonymous ones
- integral calls the function with a vector of x values, so x^2 is an invalid matrix power; write x.^2 (the result is 9)
integral evaluates the integrand at many points at once by passing a vector, and the function must return a vector of the same size. x^2 is a matrix power, which errors for a non-square vector. With x.^2 the result is 9 (exactly 3^3/3). If a function cannot be vectorized, use integral(f, 0, 3, 'ArrayValued', true).
What happens with this call?
r = fzero(@(x) x.^2 - 1, [-2 2]);- It returns -1, the first root in the interval
- It stops with an error, because the function has the same sign at both ends of the interval
- It returns 1, the positive root
- It returns 0, the midpoint where the function is smallest
When fzero gets a two-element interval it requires f(a) and f(b) to have different signs, so a bracketed root is guaranteed. Here f(-2) = f(2) = 3, both positive, so fzero errors even though roots -1 and 1 lie inside. Fix it with a bracket around one root, e.g. [0 2], or with a scalar starting point.
What does polyval([2 0 -1], 3) return?
- 17
- -7
- 5
- 1
The coefficient vector is in descending powers, so it represents 2x^2 + 0x - 1, and at x = 3 that is 18 - 1 = 17. -7 comes from reading the coefficients in ascending order (2 - 1*9), and 5 from treating the polynomial as linear (2*3 - 1).
After this call, which statement about t and y is true?
[t, y] = ode45(@(t, y) -2*y, [0 1], 1);- t is [0; 1] and y holds the solution only at these two times
- t is a column vector of time points chosen by the solver and y has one row per element of t; y(end) approximates exp(-2)
- y is a function handle that can be evaluated at any time
- t and y are row vectors of exactly 100 equally spaced points
With a two-element tspan, ode45 returns the solution at the points produced by its adaptive step-size control (plus refinement), as columns: t is n-by-1 and y is n-by-(number of states). The exact solution is y = exp(-2t), so the last row approximates exp(-2) = 0.1353. To get values at specific times pass them in tspan, e.g. 0:0.1:1, or use the one-output form sol = ode45(...) with deval.
What do trapz(y) and trapz(x, y) return?
x = 0:0.5:2;
y = x.^2;- 2.75 and 2.75
- 2.75 and 5.5
- 2.6667 and 2.6667
- 5.5 and 2.75
y = [0 0.25 1 2.25 4]. trapz(y) assumes unit spacing between points and gives 0/2 + 0.25 + 1 + 2.25 + 4/2 = 5.5; trapz(x, y) uses the real spacing 0.5 and gives 2.75. The exact integral of x^2 from 0 to 2 is 8/3 = 2.6667, which the trapezoidal rule only approximates. Forgetting to pass x is a classic mistake that scales the result by 1/h.
What does this call return?
v = interp1([1 2 3], [10 20 30], 4);- 40, extrapolated linearly
- 30, the value at the nearest end point
- NaN
- An error, because 4 is outside the data
By default interp1 interpolates only inside the range of the sample points and returns NaN for query points outside it, without an error. To extrapolate, ask for it explicitly: interp1(x, y, 4, 'linear', 'extrap') gives 40. Unnoticed NaN values from out-of-range queries often spread silently through later calculations.
The equation y'' = -y is written as a first-order system with state [y; y']. Which expression gives the position y(t) at all returned time points?
f = @(t, u) [u(2); -u(1)];
[t, U] = ode45(f, [0 pi], [0; 1]);- U(1, :)
- U(:, 2)
- U(:, 1)
- U(end)
ode45 returns one row per time point and one column per state component, so column 1 is y and column 2 is y' for every t. U(1, :) is the initial state [0 1] at t = 0, U(:, 2) is the velocity, and U(end) is a single element (the last velocity, by linear indexing). With these initial values the exact solution is y = sin(t).
Strings and cell arrays10
What does s contain?
s = ['Hello', ' ', 'world'];- 'Hello world', a 1x11 char vector
- A 1x3 cell array of words
- 'Helloworld', because the blank is dropped
- An error: use strcat to join text
Square brackets concatenate char vectors horizontally, exactly like numbers, so the result is a single char row 'Hello world' with 11 characters. Brackets do not create cell arrays (that needs braces {}). Dropping the blank is what happens with strcat, which removes trailing whitespace from char arguments; plain [] concatenation keeps it.
What are class(a) and class(b)?
c = {42, 'text', [1 2 3]};
a = c(2);
b = c{2};- 'char' and 'char'
- 'char' and 'cell'
- 'cell' and 'char'
- 'cell' and 'cell'
Parentheses index the cell array itself and return a smaller cell array (the "box"), so a is a 1x1 cell containing 'text'. Braces return the contents of the cell, so b is the char vector 'text'. Using () when you want the content is the most common cell-array mistake and leads to errors like "undefined operator for input arguments of type cell".
What is x?
x = double('42');- 42
- '42'
- An error: a string cannot be converted with double
- [52 50]
double applied to a char array returns the character codes, and the characters '4' and '2' have codes 52 and 50. To parse text as a number use str2double('42'), which returns 42 (or NaN if the text is not a number). Using double for parsing is a classic mistake because it does not error, it just gives "wrong" numbers.
What happens with this statement?
names = ['Ann'; 'Bob'; 'Kate'];- A 3x4 char matrix, with 'Ann' and 'Bob' padded with a blank
- An error, because the rows of a char matrix must all have the same length
- A 1x10 char vector 'AnnBobKate'
- A 3x1 cell array of names
A char matrix is a rectangular array of characters, and vertical concatenation with ; requires equal row lengths: 'Kate' has 4 characters, the others 3, so MATLAB raises a dimension error. char('Ann', 'Bob', 'Kate') pads with blanks automatically, while a cell array {'Ann'; 'Bob'; 'Kate'} or a string array keeps texts of different lengths without padding.
What does this expression return?
'ab' + 'cd'- 'abcd'
- An error, because + is not defined for text
- [196 198]
- 394
Single quotes create char arrays, and arithmetic on chars works on their character codes: 'a' + 'c' = 97 + 99 = 196 and 'b' + 'd' = 98 + 100 = 198, giving a double row vector. Concatenation of char vectors is ['ab' 'cd']. (In MATLAB, "ab" + "cd" with double quotes creates string objects and does give "abcd"; in Octave double quotes still mean char, so it gives [196 198] as well.)
How do you read the age field of this structure?
s.name = 'Ann';
s.age = 31;- s{'age'}
- s.age
- s('age')
- s->age
Structure fields are accessed with a dot: s.age returns 31. For a field name stored in a variable use dynamic field syntax s.(fname). Braces are for cell arrays, parentheses index the struct array itself, and -> is C/C++ pointer syntax that MATLAB does not have.
a = 'cat' and b = 'cats'. Which expression safely tests whether the two char vectors are equal?
- a == b
- all(a == b)
- strcmp(a, b)
- a = b
strcmp compares the whole texts and returns logical 0 or 1 for any lengths (here 0). == compares character by character and raises an error because the arrays have 3 and 4 elements, so all(a == b) fails too; for equal-length texts it would return an array, not one answer. a = b is an assignment, not a comparison.
What does c{3}(2) return?
c = {42, 'text', [1 2 3]};- An error: a cell array cannot be indexed twice
- 'e'
- {2}
- 2
c{3} extracts the contents of the third cell, the numeric vector [1 2 3], and (2) then indexes that vector, giving 2. Chained indexing like this is allowed. 'e' would be c{2}(2), the second character of 'text', and the result is a number, not a cell, because the braces already removed the cell wrapper.
What does size(s) return?
s = struct('x', {1, 2, 3});- [1 1], and s.x is the cell array {1, 2, 3}
- [1 3]: a struct array whose elements have x = 1, 2 and 3
- [1 1], and s.x is the vector [1 2 3]
- An error, because a value must not be a cell array
When struct gets a cell array as a field value, it creates a struct array with one element per cell, so s is 1x3 and s(2).x is 2. To store a cell array itself in a single struct, wrap it in another cell: struct('x', {{1, 2, 3}}). This rule surprises many users who build structs from cell data.
What is s(2).age after this code?
s(1).name = 'Ann';
s(1).age = 31;
s(2).name = 'Bob';- 31, copied from s(1)
- [] (an empty array)
- An error: s(2) has no field age
- 0
All elements of a struct array share the same set of fields. Adding s(2) with only name set still gives it an age field, initialised to the empty array []. Values are not copied from other elements and are not zero. Code that later uses s(k).age in arithmetic then produces empty results, a common surprise.
Performance and pitfalls10
What does this comparison return?
0.1 + 0.2 == 0.3- 0 (logical false)
- 1 (logical true)
- 0.3000
- An error, because == cannot compare floating-point numbers
0.1, 0.2 and 0.3 cannot be stored exactly in binary floating point, and the rounded sum 0.1 + 0.2 is 0.30000000000000004, one ulp away from the stored 0.3, so == is false. The display 0.3000 hides the difference because format short shows only 4 decimals. Compare floating-point results with a tolerance, e.g. abs(a - b) < 1e-12.
Why is it recommended to write x = zeros(1, n) before a loop that fills x(k) for k = 1:n?
- Because assigning x(k) to a variable that does not exist yet is an error
- Because zeros makes x an integer array, which is faster
- Because otherwise x grows by one element per iteration, and MATLAB may have to reallocate and copy the whole array each time
- Because preallocation makes the loop run on several CPU cores
Assigning past the end of an array is allowed in MATLAB, it simply grows the array, so the code works without preallocation, only slower: each growth may need a new memory block and a copy, which makes the loop O(n^2) in the worst case. zeros creates a double array, not an integer one, and preallocation has nothing to do with parallelism. The Code Analyzer warns "variable appears to change size on every loop iteration".
What does this expression return?
int8(100) + int8(100)- 200
- -56, because the value wraps around
- 127
- An error: integer overflow
MATLAB integer arithmetic saturates: results outside the range of the type are clamped to the nearest limit, and int8 holds -128..127, so the result is int8(127). C-style wrap-around (-56) does not happen, and there is no overflow error, which makes saturation bugs easy to miss in image processing with uint8 data. Convert to double first if you need the exact value.
What does eps (called with no arguments) represent in double precision?
- The smallest positive number that can be stored, about 2.2251e-308
- The distance from 1.0 to the next larger double, about 2.2204e-16
- Exactly 1e-16, the error of every arithmetic operation
- The tolerance that == uses when it compares doubles
eps = 2^-52, the gap between 1 and the next representable double; it measures relative precision, and eps(x) gives the gap near x. The smallest positive normalized double is realmin (about 2.2251e-308), a completely different quantity. == does not use any tolerance: it compares exactly, which is why 0.1 + 0.2 == 0.3 is false.
What does this expression return?
int32(7) / int32(2)- 3, because integer division truncates
- 3.5000, of class double
- An error: use idivide for integers
- 4, of class int32
Integer arithmetic in MATLAB is computed as if in exact arithmetic and then rounded to the nearest integer (halves away from zero), so 3.5 becomes 4 and the result stays int32. Expecting 3 is the habit from C or Java, where integer division truncates. When you want truncation or floor division, use idivide(int32(7), int32(2)) (default 'fix') or floor on doubles.
a and b are results of floating-point computations that should be mathematically equal. Which test is appropriate?
- a == b
- isequal(a, b)
- round(a) == round(b)
- abs(a - b) < tol, with a small tolerance tol suited to the magnitude of the values
Rounding errors make computed values that are equal on paper differ in the last bits, so == and isequal (which also compares exactly) can return false. Rounding to integers throws away almost all precision and only works for integer-valued results. Comparing the difference with a tolerance, often relative like abs(a - b) <= 1e-12 * max(abs(a), abs(b)), is the robust approach.
Which statement is the vectorized equivalent of this loop for a row vector x?
for k = 1:numel(x)
y(k) = x(k)^2;
end- y = x^2;
- y = x * x;
- y = sum(x.^2);
- y = x.^2;
Vectorized code applies the operation to the whole array at once: x.^2 squares every element and returns an array the same size as x, usually much faster than a loop that also grows y. x^2 and x * x are matrix operations that fail for a row vector, and sum(x.^2) collapses the result to a single number.
What does this expression return?
uint8(5) - uint8(10)- -5
- 251, because the value wraps around
- 0
- An error, because the result is negative
uint8 holds values 0..255 and MATLAB integer arithmetic saturates at the range limits, so a negative result becomes 0. There is no wrap-around to 251 as in C, and no error. This often bites in image processing: subtracting two uint8 images clips negative differences to 0; convert to double (or int16) first, or use imabsdiff.
What does this expression return?
int8(10) * 0.26- 2.6000, of class double
- 2, of class int8
- 3, of class int8
- An error: integers can only be combined with integers of the same class
An integer may be combined with a double scalar; the operation is done in double precision and the result is converted back to the integer class, rounding to the nearest integer. 10 * 0.26 = 2.6 rounds to 3 and the class is int8. Expecting a double result or truncation to 2 are the typical mistakes. Mixing two different integer classes (e.g. int8 with int16) is what raises an error.
What does the second line return?
x = 2^53;
x + 1 == x- 0 (false), since adding 1 always changes a number
- 1 (true)
- An error: integer overflow
- NaN
Doubles have a 53-bit significand, so above 2^53 the gap between neighbouring doubles is 2. 2^53 + 1 lies exactly halfway and is rounded back to 2^53, so the comparison is true. There is no overflow error for doubles; flintmax (= 2^53) is the largest value up to which every integer is represented exactly. Use int64/uint64 if you need exact integers beyond that.
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Basics and syntax 10
- Vectors and matrices 10
- Indexing 10
- Element-wise vs matrix operations 10
- Control flow and functions 10
- Linear algebra 10
- Plotting 10
- Numerical methods 10
- Strings and cell arrays 10
- Performance and pitfalls 10
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по языку C100 вопросовТест по COBOL100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
