Type checking (class, isa) in MATLAB - Time & Space Complexity
We want to understand how long it takes to check the type of a variable in MATLAB.
How does the time needed change when we check many variables or objects?
Analyze the time complexity of the following code snippet.
for i = 1:n
if isa(data{i}, 'double')
disp('Number')
elseif isa(data{i}, 'char')
disp('Text')
else
disp('Other')
end
end
This code checks the type of each element in a cell array and prints a message based on its type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runsisachecks on each element. - How many times: The loop runs
ntimes, once per element in the input array.
Each new element adds one more type check, so the total work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The work grows directly in proportion to the number of elements.
Time Complexity: O(n)
This means the time to check types grows in a straight line as the number of elements increases.
[X] Wrong: "Type checking is instant and does not depend on how many items we check."
[OK] Correct: Each item requires a separate check, so more items mean more time spent.
Knowing how type checks scale helps you write efficient code when handling many variables or objects.
"What if we replaced the for loop with a vectorized function that checks all types at once? How would the time complexity change?"