Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 45 ยท Practice and Review

Interview Questions

Prepare for MATLAB and Octave interviews with clear answers on arrays, vectorization, cells vs structs, performance and floating-point numerics.

Interviewers for engineering, data and research roles rarely ask for obscure syntax. They want to see that you understand how MATLAB and Octave think: everything is an array, memory is laid out in columns, operators have matrix and element-wise forms, and numbers are finite-precision approximations. This lesson collects the concept questions that come up most often, each with a short model answer you can say out loud.

Read the answers as a guide, not a script. A strong reply states the rule, gives a tiny example, and mentions the common mistake. If you can explain why, the exact function names matter much less.

MATLAB and Octave are not installed on this site, so the matlab snippets are read-only. The TryIt editors are Python (NumPy) stand-ins that demonstrate the same ideas, and the text says where the stand-in differs.

Five interview themes

Arrays Column-major, indexing, copies.
Vectorization Whole-array thinking.
Cells and structs Mixed data containers.
Performance Preallocation and profiling.

Numerics is the fifth theme, covered at the end.

1 / 2

Arrays and indexing

What is the basic data type in MATLAB?

The array. A scalar is a 1-by-1 array, a vector is 1-by-n or n-by-1, and a matrix is m-by-n. Higher dimensions exist too. The default numeric class is double (64-bit floating point), which is why x = 5 creates a double unless you ask for something else.

In what order is a matrix stored in memory?

Column by column, called column-major order (the same as Fortran). For A = magic(3) the memory order is 8, 3, 4, 1, 5, 9, 6, 7, 2, so the linear index A(4) is 1, the top of the second column. This is why loops should walk down columns in the inner loop, and why A(:) stacks columns into one tall vector.

How is MATLAB indexing different from Python's?

Indices start at 1, ranges include both ends (x(2:4) is elements 2, 3 and 4), end means the last position, and a single index on a matrix counts down the columns. Parentheses are used for both indexing and function calls, which is an old quirk of the language. Negative indices are not allowed and an index of 0 raises an error.

What is the difference between * and .*?

* is matrix multiplication and requires the inner dimensions to agree. .* multiplies element by element and requires the sizes to match or be compatible through implicit expansion. The same split exists for / and ./, and for ^ and .^. Using * where you meant .* is the most common beginner bug and usually ends in a dimension error, or worse, a silent wrong answer when both operands happen to be square.

What is implicit expansion?

When two arrays differ in a dimension and one of the sizes is 1, MATLAB stretches the singleton dimension virtually. A 3-by-1 column plus a 1-by-4 row gives a 3-by-4 matrix. It replaces older tricks such as repmat or bsxfun, and it lets you subtract a column mean from every column without a loop. Octave supports it too (it called it broadcasting).

Python Column-major order and implicit expansion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NumPy calls the same rule broadcasting and applies it automatically. Note that NumPy stores arrays in row-major order by default, so order="F" is needed to mimic MATLAB's memory order.

Does assigning one array to another copy it?

Conceptually yes: arrays have value semantics. After B = A; B(1) = 99, the array A is unchanged. Internally MATLAB uses copy-on-write, so no memory is duplicated until one of them is modified. Objects that inherit from handle are the exception, because they behave like references.

How do you grow an array, and what is the cost?

v(end+1) = x appends an element, but it may reallocate and copy the whole array each time, which is slow inside a long loop. If you know the final size, preallocate with zeros, nan or cell. If you do not, collect values in a loop and trim afterwards, or use a cell array.

Vectorization

What is vectorization and why does it matter?

Writing operations on whole arrays instead of element-by-element loops. The code is shorter and closer to the maths, and the heavy lifting runs in optimized compiled libraries. In Octave, the difference from loops is large because loops are interpreted. Modern MATLAB has a just-in-time compiler that makes simple loops much faster than they once were, but vectorized code usually remains clearer and often faster.

Name three vectorization tools.

  • Element-wise operators and functions: y = x.^2 + 3*x.
  • Logical indexing instead of if inside a loop: x(x < 0) = 0.
  • Cumulative and difference functions: cumsum, cumprod, diff, cummax.

Others are implicit expansion, sum/mean along a dimension, sort, histcounts and matrix multiplication for sums of products.

When is a loop still the right choice?

When each iteration depends on the previous result in a way no built-in expresses (for example a custom iterative solver), when the loop body is large and readable, or when memory is tight and a full intermediate array would be huge. Measure before rewriting.

How would you replace this loop?

MATLAB
total = 0;
for k = 1:numel(x)
    if x(k) > 0
        total = total + x(k)^2;
    end
end

With a mask: total = sum(x(x > 0).^2). The mask selects the positive elements, .^2 squares each, and sum adds them up.

Cells and structs

What is a cell array?

A container whose elements can have different types and sizes, such as a number, a string and a matrix side by side. You create one with braces: c = {1, 'text', [1 2 3]}.

What is the difference between c(2) and c{2}?

Parentheses return a sub-cell (a 1-by-1 cell array), while braces return the contents of that cell. So c(2) is still a cell, and c{2} is the character array 'text'. A beginner error is trying to do arithmetic on c(1) when c{1} was meant.

When would you use a struct instead of a cell array?

When the pieces have meaning, so you want to refer to them by name: person.name, person.age. A struct array (people(3).name) holds many records with the same fields. Cell arrays suit collections of unlabelled items of different types, and structs suit records. Dynamic field names, s.(fieldName), let you choose the field at run time.

Is a struct array of records or a struct of arrays better?

It depends on usage. An array of structs (people(k).age) is natural for a list of records, but collecting all ages needs [people.age]. A struct of arrays (data.age is a vector) is faster for numeric work on one field, and each field then stays a plain numeric array. Large numeric tables are usually better stored as a struct of arrays or as a table.

Python Cells and structs through Python containers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in matches the idea. In real MATLAB, c(2) is a 1-by-1 cell, which a Python one-element list imitates well.

Performance

How do you find out why code is slow?

Measure first. tic and toc time a block, timeit gives a more reliable estimate for a function, and the Profiler (profile on, profile viewer) shows which lines cost the most. Octave has a similar profile command. Most slowness comes from growing arrays in loops, repeated work inside loops, and calling scripts or functions with heavy overhead millions of times.

What is preallocation?

Creating an array of the final size before the loop and filling it in: out = zeros(1, n). That avoids repeated reallocation and copying, and it makes the code easier to read.

Why does loop order matter?

Because of column-major storage, elements in the same column are next to each other in memory. An inner loop over rows touches memory sequentially, while an inner loop over columns jumps around and wastes cache. The effect shows most on large matrices.

Does a parallel for always speed things up?

No. parfor (Parallel Computing Toolbox in MATLAB) helps when iterations are independent and each does enough work to pay for the communication overhead. Tiny loop bodies and shared mutable state are bad candidates.

Numerics

Why is 0.1 + 0.2 == 0.3 false?

Doubles store binary fractions, and 0.1, 0.2 and 0.3 have no exact binary form. The sum differs from 0.3 in the last bit. Compare with a tolerance: abs(a - b) < 1e-9, or relative to the size of the numbers. eps is the spacing of doubles around 1, about 2.2e-16.

What happens with integer types?

Integer classes such as uint8 and int16 saturate instead of wrapping around: uint8(200) + 100 is 255, and uint8(5) - 10 is 0. They also round to the nearest integer, with halves going away from zero, so int8(2.5) is 3. Mixed arithmetic between different integer classes is an error, but integer-with-double is allowed and yields the integer class.

Why prefer A\b over inv(A)*b?

Backslash solves the system directly with a factorization. It is faster, usually more accurate, and it warns you about singular or badly scaled matrices. Computing an explicit inverse is rarely necessary. If you need to solve for many right-hand sides, factor once with lu or decomposition and reuse it.

How should you handle NaN and Inf?

NaN means "not a number" and is not equal to anything, including itself, so use isnan. Division by zero gives Inf (not an error). Statistics such as mean return NaN if any element is NaN unless you pass 'omitnan' (a feature that older Octave versions lack).

Python Floating-point, saturation and conditioning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NumPy's own round sends halves to the nearest even number, which differs from MATLAB. That is why the stand-in defines matlab_round.

What is the difference between & and &&?

& works element by element on arrays. && is a short-circuit operator for scalar conditions: the right side is skipped when the left side decides the result, which makes isempty(x) || x(1) > 0 safe. Use && inside if and while conditions, and & for masks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For A = magic(3) stored column by column, what does A(4) refer to?

    A single subscript is a linear index that counts down the columns, so the 4th element is the top of column 2.
  2. 2. What is the difference between c(2) and c{2} for a cell array c?

    Parentheses select a sub-cell, braces extract what is inside it.
  3. 3. What does uint8(200) + 100 return?

    Integer classes saturate at their maximum value instead of wrapping around, so the result is 255.
  4. 4. Why is A\b usually preferred over inv(A)*b?

    Backslash uses a factorization to solve the system directly, which avoids the extra work and the rounding error of forming an inverse.

Summary

  • Everything is an array, stored column by column, indexed from 1, with linear indexing that counts down columns.
  • *, / and ^ are matrix operators; the dotted forms work element by element, and implicit expansion stretches singleton dimensions.
  • Vectorize with element-wise math, logical masks and cumulative functions, but measure with tic/toc or the profiler before optimizing.
  • Cells hold unlabelled mixed items ({} for contents, () for sub-cells); structs hold named fields; preallocate arrays before loops.
  • Floating-point numbers are approximations, integers saturate, NaN needs isnan, and A\b beats inv(A)*b.

Next: keep a one-page reference at hand with the MATLAB / Octave Cheat Sheet.