Parse a MATLAB Matrix Literal Into Nested Rows
Last updated: November 29, 2026
Quick Overview
Write a function that parses a MATLAB-style matrix literal such as '[1 2 3; 4,5,6]' into a list of numeric rows, accepting spaces or commas between elements and semicolons or newlines between rows, and rejecting rows of unequal length.
MathWorks
November 29, 20260
0
0 solved
Write a function that parses a MATLAB-style matrix literal such as '[1 2 3; 4,5,6]' into a list of numeric rows, accepting spaces or commas between elements and semicolons or newlines between rows, and rejecting rows of unequal length.
MathWorks online assessments often use small parsing tasks drawn from MATLAB itself, since the company builds the language. The grader checks careful tokenization, sensible error messages that mirror MATLAB's own, and attention to separators and blank rows.
What the Interviewer Expects
- Splits rows on both ';' and newline, elements on both ',' and whitespace
- Converts tokens to int or float, including scientific notation
- Raises a clear error for unequal row lengths, matching MATLAB's concatenation error
- Tolerates trailing semicolons and the empty matrix []
- Calls out the ambiguity of '1 -2' versus '1 - 2'
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- MATLAB reads [1 -2] as two elements but [1 - 2] as one; how would you implement that rule?
- How would you extend the parser to support nested brackets like [A, B; C] that concatenate submatrices?
- How would you add complex literals such as 3+4i?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: a string starting with [ and ending with ]. Output: list of rows, each a list of numbers. Element separators: comma or whitespace. Row separators: semicolon or newline. Empty rows (from tra...
High-Level Design
Strip the brackets, normalize newlines to semicolons, and split into raw rows. For each row, turn commas into spaces and split on whitespace to get tokens. Parse each token as an int unless it contain...