MATLAB (Matrix Laboratory) is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages.
MATLAB Anti-Patterns Overview
Growing Arrays in Loops
Using Loops Instead of Vectorization
Using eval and str2func
eval
and str2func
with dynamically constructed strings. These functions can execute arbitrary code, making your program vulnerable to code injection if the strings come from external sources. They also make code harder to debug and maintain. Use arrays, cell arrays, or containers.Map to store multiple values or function handles instead.Using Global Variables
Not Using Functions for Code Organization
Using clear all/close all/clc
clear all
, close all
, and clc
in scripts and functions, especially those that might be called by other scripts or functions. These commands affect the entire MATLAB environment, not just your script’s scope, which can lead to unexpected behavior and make debugging more difficult. Instead, be specific about what variables to clear and what figures to close.Not Handling Errors Properly
Using i and j as Variable Names
i
and j
as variable names, especially for loop indices. In MATLAB, i
and j
are predefined as the imaginary unit (√-1), and overwriting them can lead to unexpected behavior in complex arithmetic. Use ii
, jj
, or other names for loop indices, and consider using 1i
instead of i
for the imaginary unit.Using Magic Numbers
pi
).Ignoring Code Vectorization Opportunities
Not Using Logical Indexing
Inefficient File I/O
textscan
, readtable
, readmatrix
, or readlines
(in newer versions) to read the entire file at once. These functions are optimized for performance and make your code more concise.Not Using Built-in Functions
Using Nested Loops for Matrix Operations
*
, '
, and functions like inv
instead of implementing these operations manually.Not Using Appropriate Data Structures
Not Using Cell Arrays Appropriately
Not Using Function Handles
Not Using Profiler for Performance Optimization
Not Using Appropriate Comments and Documentation
help
command.Not Using Meaningful Variable Names
i
and j
for loop indices, but even then, be careful as mentioned earlier).