Okay, here is the detailed article on the MATLAB isempty
function.
MATLAB Tutorial: Mastering the isempty
Function for Robust Code
Introduction: The Ubiquitous Need for Emptiness Detection
In the dynamic world of MATLAB programming, data is king. We manipulate matrices, process signals, analyze datasets, and build complex models. However, not all data arrives perfectly formed or persists throughout our computations. Variables can be intentionally created as empty placeholders, become empty as a result of filtering or subsetting operations, or be returned as empty from functions indicating specific conditions like “not found” or “no results.”
Handling these “empty” states gracefully is not just good practice; it’s fundamental to writing robust, error-free, and efficient MATLAB code. Attempting operations like indexing, mathematical calculations, or even looping on an empty array often leads to runtime errors, unexpected behavior, or crashes. This is where MATLAB’s built-in function, isempty
, becomes an indispensable tool in the programmer’s arsenal.
The isempty
function provides a simple, efficient, and idiomatic way to determine if a variable contains an empty array. Understanding its nuances, how it behaves with different data types, and its various practical applications is crucial for any MATLAB user, from beginner to expert. Ignoring emptiness checks can lead to fragile code that breaks under seemingly innocuous conditions. Conversely, mastering isempty
empowers you to write defensive code that anticipates and correctly handles situations involving missing or absent data.
This comprehensive tutorial aims to provide a deep dive into the isempty
function. We will explore:
- What constitutes an “empty” variable in the MATLAB context, distinguishing it from zero, NaN, or missing values.
- The fundamental syntax and behavior of the
isempty
function. - How
isempty
interacts with various fundamental MATLAB data types, including numeric arrays, character vectors, string arrays, cell arrays, structures, tables, and more. - Numerous practical use cases where
isempty
is essential for controlling program flow, validating inputs, handling function outputs, cleaning data, and preventing errors. - Advanced considerations, edge cases, and performance aspects.
- Common pitfalls and mistakes to avoid when using
isempty
. - Alternatives to
isempty
and when they might (or might not) be appropriate. - Best practices for incorporating emptiness checks into your MATLAB workflows.
By the end of this article, you will have a thorough understanding of isempty
and be well-equipped to use it effectively to enhance the reliability and sophistication of your MATLAB programs. Let’s embark on this journey to master the detection of emptiness in MATLAB.
Defining Emptiness in MATLAB: More Than Just Nothing
Before diving into the function itself, it’s critical to understand precisely what MATLAB considers “empty.” In MATLAB, arrays are the fundamental data structure. An array is considered empty if at least one of its dimensions has a size of zero.
Think of a matrix (a 2D array). Its size is defined by [rows, columns]
.
* A 0x5
matrix is empty (zero rows).
* A 5x0
matrix is empty (zero columns).
* A 0x0
matrix is empty (zero rows and zero columns).
* A 3x4
matrix is not empty.
This concept extends to arrays of any dimension. A 4x0x3
array is empty because its second dimension has size zero. A 0x1x1x5
array is empty because its first dimension has size zero.
Common Empty Arrays:
The most frequently encountered empty array is the empty double-precision matrix, created using empty square brackets:
“`matlab
emptyNumeric = [];
whos emptyNumeric
Name Size Bytes Class Attributes
emptyNumeric 0x0 0 double
“`
Notice the size is 0x0
.
This definition applies across different data types:
- Empty Character Array:
''
(Size:1x0
or sometimes0x0
depending on context/creation method, but always considered empty byisempty
).
matlab
>> emptyChar = '';
>> whos emptyChar
Name Size Bytes Class Attributes
emptyChar 1x0 0 char - Empty String Array:
""
(Represents a single string scalar with zero characters, or an empty array of strings).strings(0,1)
orstrings(1,0)
orstrings(0,0)
are definitively empty arrays of strings.
matlab
>> emptyStrArray = strings(0,1);
>> whos emptyStrArray
Name Size Bytes Class Attributes
emptyStrArray 0x1 0 string
Note:""
itself is a scalar string (size 1×1) containing zero characters.isempty("")
isfalse
. This is a crucial distinction we’ll revisit. - Empty Cell Array:
{}
(Size:0x0
).
matlab
>> emptyCell = {};
>> whos emptyCell
Name Size Bytes Class Attributes
emptyCell 0x0 0 cell -
Empty Structure Array:
struct()
with no fields, or an array of structs with a zero dimension.
“`matlab
>> emptyStructArray = struct([]); % Creates a 0x0 struct array with no fields
>> whos emptyStructArray
Name Size Bytes Class Attributes
emptyStructArray 0x0 0 structs = struct(‘field1’, {}); % Creates a struct with an empty field value (cell array)
emptyStructArrayDim = repmat(s, 0, 1); % Creates a 0x1 struct array
whos emptyStructArrayDim
Name Size Bytes Class Attributes
emptyStructArrayDim 0x1 0 struct
* **Empty Table:** `table()` or a table with zero rows.
matlab
emptyTable = table(); % Creates a 0x0 table
whos emptyTable
Name Size Bytes Class Attributes
emptyTable 0x0 0 tableT = table([1;2], {‘a’;’b’}, ‘VariableNames’, {‘Num’,’Str’});
emptyTableRows = T(false(2,1), :); % Select zero rows
whos emptyTableRows
Name Size Bytes Class Attributes
emptyTableRows 0x2 136 table % Bytes non-zero due to metadata
“`
Crucial Distinctions: Empty vs. Other “Non-Value” Concepts
It is vital not to confuse an empty array with arrays containing specific values like zero, space, NaN (Not-a-Number), or <missing>
(for specific data types like string
, datetime
, categorical
).
- Zero (
0
): A numeric array containing the value0
is not empty. It has one element.
matlab
>> x = 0;
>> size(x)
ans =
1 1
>> isempty(x)
ans =
logical
0 % False - Space (
' '
): A character array containing a space is not empty. It has one character.
matlab
>> c = ' ';
>> size(c)
ans =
1 1
>> isempty(c)
ans =
logical
0 % False - NaN (
NaN
): A numeric array containingNaN
is not empty. It holds a specific numeric value representing “Not-a-Number.”
matlab
>> n = NaN;
>> size(n)
ans =
1 1
>> isempty(n)
ans =
logical
0 % False -
Missing (
<missing>
): A string array element"<missing>"
or a categorical<undefined>
is not an empty array. It’s a specific value indicating missing data within a non-empty array.
“`matlab
>> str_miss = ““; % A 1×1 string array
>> isempty(str_miss)
ans =
logical
0 % Falsecat_undef = categorical(NaN); % Creates a 1×1
categorical
isempty(cat_undef)
ans =
logical
0 % False
“`
Understanding this precise definition of emptiness – having at least one dimension of size zero – is the foundation for using isempty
correctly.
Introducing isempty
: Syntax and Basic Operation
The isempty
function is refreshingly simple in its syntax and core operation.
Syntax:
matlab
tf = isempty(A)
A
: The input variable (which is always an array in MATLAB) that you want to check for emptiness.tf
: The output, which is a logical scalar (eithertrue
orfalse
).tf
istrue
(logical1
) ifA
is an empty array (i.e., if any dimension ofA
has size 0).tf
isfalse
(logical0
) ifA
is not an empty array (i.e., all dimensions have size greater than 0).
Basic Examples:
“`matlab
% Numeric Arrays
A = [];
isempty(A)
ans =
logical
1B = [1 2 3];
isempty(B)
ans =
logical
0C = zeros(5, 0); % 5 rows, 0 columns
isempty(C)
ans =
logical
1D = zeros(0, 5); % 0 rows, 5 columns
isempty(D)
ans =
logical
1
% Character Arrays
E = ”;
isempty(E)
ans =
logical
1F = ‘hello’;
isempty(F)
ans =
logical
0G = ‘ ‘; % Contains a space
isempty(G)
ans =
logical
0
% Cell Arrays
H = {};
isempty(H)
ans =
logical
1I = {1, ‘a’, []}; % Contains 3 elements, one of which is itself empty
isempty(I)
ans =
logical
0 % The cell array I itself is not empty
% Structure Arrays
J = struct([]);
isempty(J)
ans =
logical
1K = struct(‘name’, ‘John’, ‘age’, 30); % A 1×1 struct array
isempty(K)
ans =
logical
0
“`
The function works reliably and predictably based on the array’s dimensions. Its simplicity is its strength, providing a clear and unambiguous answer to the question: “Does this array have a dimension of size zero?”
Deep Dive: isempty
Across MATLAB Data Types
While the core principle remains the same (checking dimensions), the nuances of how empty arrays are created and represented differ slightly across data types. Let’s explore isempty
‘s behavior with common MATLAB data types in more detail.
1. Numeric Arrays (double, single, integers, logical)
This is the most straightforward case. Any numeric array created with a zero in any of its dimension sizes will return true
from isempty
.
“`matlab
emptyDouble = []; % 0x0 double
isempty(emptyDouble)
ans = logical
1emptySingle = single([]); % 0x0 single
isempty(emptySingle)
ans = logical
1emptyInt = int8([]); % 0x0 int8
isempty(emptyInt)
ans = logical
1emptyLogical = logical([]); % 0x0 logical
isempty(emptyLogical)
ans = logical
1matrixA = rand(3, 0, 4); % 3x0x4 double
isempty(matrixA)
ans = logical
1matrixB = ones(2, 2); % 2×2 double
isempty(matrixB)
ans = logical
0scalarZero = 0; % 1×1 double
isempty(scalarZero)
ans = logical
0vectorNaN = [NaN NaN]; % 1×2 double
isempty(vectorNaN)
ans = logical
0
“`
Key Takeaway: For numeric types, isempty
strictly checks dimensions. The values (0, NaN, Inf) within the array do not make the array itself empty.
2. Character Arrays (char)
Character arrays (often called “strings” in other languages, but distinct from MATLAB’s string
type) are typically vectors or matrices of characters. An empty character array is created with single quotes ''
.
“`matlab
emptyChar1 = ”;
whos emptyChar1
Name Size Bytes Class Attributes
emptyChar1 1×0 0 char
isempty(emptyChar1)
ans = logical
1
% Sometimes MATLAB creates 0x0 char arrays
emptyChar2 = char([]);
whos emptyChar2
Name Size Bytes Class Attributes
emptyChar2 0x0 0 char
isempty(emptyChar2)
ans = logical
1non পাশ্চemptyChar = ‘MATLAB’; % 1×6 char
isempty(nonEmptyChar)
ans = logical
0spaceChar = ‘ ‘; % 1×1 char containing a space
isempty(spaceChar)
ans = logical
0
“`
Key Takeaway: isempty('')
is true
. isempty(' ')
is false
. This is a common point of confusion; isempty
checks for an empty array, not necessarily an empty string in the semantic sense (like zero printable characters). To check if a char array contains only whitespace, you would need different functions (e.g., strtrim
, isspace
).
3. String Arrays (string)
MATLAB’s string
type (introduced in R2016b) handles text data differently from char
. A string
array can contain multiple individual strings.
- An empty array of strings is created using
strings(m, n, ...)
where at least one dimension is zero. - A scalar string containing zero characters is created with double quotes
""
.
This distinction is critical for isempty
.
“`matlab
emptyStringArray1 = strings(0, 3); % 0x3 string array
isempty(emptyStringArray1)
ans = logical
1emptyStringArray2 = strings(2, 0); % 2×0 string array
isempty(emptyStringArray2)
ans = logical
1zeroCharString = “”; % A 1×1 string array containing a single string with 0 characters
whos zeroCharString
Name Size Bytes Class Attributes
zeroCharString 1×1 114 string
isempty(zeroCharString)
ans = logical
0 % CRITICAL: It’s a 1×1 array, so not empty!nonEmptyStringArray = [“Hello”, “World”]; % 1×2 string array
isempty(nonEmptyStringArray)
ans = logical
0stringWithMissing = [“A”, “
“, “C”]; % 1×3 string array
isempty(stringWithMissing)
ans = logical
0 % Contains elements, even if one is
“`
Key Takeaway: isempty
checks if the string array itself has a zero dimension. It does not check if the strings within the array have zero length. isempty("")
is false
. To check for zero-length strings within a string array, you would use strlength(strArray) == 0
. To check for <missing>
strings, use ismissing(strArray)
.
4. Cell Arrays (cell)
Cell arrays store collections of potentially different data types. An empty cell array is created with curly braces {}
.
“`matlab
emptyCellArray1 = {}; % 0x0 cell array
isempty(emptyCellArray1)
ans = logical
1emptyCellArray2 = cell(0, 5); % 0x5 cell array
isempty(emptyCellArray2)
ans = logical
1nonEmptyCell = {1, ‘two’, [], rand(2)}; % 1×4 cell array
isempty(nonEmptyCell)
ans = logical
0 % The cell array itself is not empty…isempty(nonEmptyCell{3}) % …but its third element IS empty
ans = logical
1
“`
Key Takeaway: isempty
checks the dimensions of the cell array container, not the contents of its cells. A cell array can be non-empty but contain empty arrays within its cells.
5. Structure Arrays (struct)
Structures group related data using named fields. An empty structure array has at least one dimension of size zero. This can be created using struct([])
or by indexing/replication that results in a zero dimension.
“`matlab
emptyStructArray1 = struct([]); % 0x0 struct array with 0 fields
isempty(emptyStructArray1)
ans = logical
1emptyStructArray2 = struct(‘fieldA’, {}, ‘fieldB’, {}); % 0x0 struct with 2 fields
whos emptyStructArray2
Name Size Bytes Class Attributes
emptyStructArray2 0x0 32 struct % Bytes non-zero due to field names
isempty(emptyStructArray2)
ans = logical
1s = struct(‘name’, ‘Data’, ‘value’, 10); % 1×1 struct array
emptyStructArray3 = repmat(s, 0, 1); % Create a 0x1 version
isempty(emptyStructArray3)
ans = logical
1nonEmptyStruct = struct(‘name’, ‘Test’, ‘value’, pi); % 1×1 struct
isempty(nonEmptyStruct)
ans = logical
0
% Struct with empty FIELD values
structWithEmptyFields = struct(‘data’, [], ‘label’, ”); % 1×1 struct
isempty(structWithEmptyFields)
ans = logical
0 % The struct itself (1×1) is not empty…isempty(structWithEmptyFields.data) % …but the ‘data’ field IS empty
ans = logical
1
isempty(structWithEmptyFields.label) % …and the ‘label’ field IS empty
ans = logical
1
“`
Key Takeaway: isempty
checks the dimensions of the structure array, not whether the fields within the struct(s) contain empty values. Use dot notation (.
) to access and check individual fields if needed.
6. Tables (table)
Tables are designed for columnar data, potentially of mixed types, with row and variable names. An empty table typically has zero rows.
“`matlab
emptyTable1 = table(); % 0x0 table
isempty(emptyTable1)
ans = logical
1emptyTable2 = table(‘Size’, [0, 3], ‘VariableTypes’, {‘double’, ‘string’, ‘logical’}); % 0x3 table
whos emptyTable2
Name Size Bytes Class Attributes
emptyTable2 0x3 352 table % Metadata takes space
isempty(emptyTable2)
ans = logical
1
% Create a non-empty table
T = table(rand(3,1), {‘X’;’Y’;’Z’}, categorical({‘A’;’B’;’A’}), …
‘VariableNames’, {‘Value’, ‘ID’, ‘Category’});
isempty(T)
ans = logical
0
% Select zero rows from a non-empty table
emptyRowsTable = T(1:0, :); % Or T([], 🙂 or T(false(3,1), 🙂
whos emptyRowsTable
Name Size Bytes Class Attributes
emptyRowsTable 0x3 352 table
isempty(emptyRowsTable)
ans = logical
1
“`
Key Takeaway: For tables, isempty
typically corresponds to checking if the table has zero rows (height(T) == 0
or size(T, 1) == 0
), which is the most common definition of an “empty” table in practice.
7. Categorical Arrays (categorical)
Categorical arrays store data from a finite set of discrete categories. An empty categorical array has a zero dimension.
“`matlab
emptyCat1 = categorical([]); % 0x0 categorical
isempty(emptyCat1)
ans = logical
1emptyCat2 = categorical(strings(0, 2)); % 0x2 categorical
isempty(emptyCat2)
ans = logical
1non পাশ্চemptyCat = categorical({‘Red’, ‘Green’, ‘Blue’, ‘Red’}); % 1×4 categorical
isempty(nonEmptyCat)
ans = logical
0catWithUndefined = categorical({‘Low’, NaN, ‘High’}); % 1×3 categorical with
isempty(catWithUndefined)
ans = logical
0 % Array is 1×3, not emptyisundefined(catWithUndefined(2)) % Check for
element specifically
ans = logical
1
“`
Key Takeaway: isempty
checks the categorical array’s dimensions. It does not check for the presence of <undefined>
elements within the array. Use isundefined
for that purpose.
8. Function Handles (@)
Function handles are references to functions. They are typically scalar (1×1).
“`matlab
fh = @sin;
whos fh
Name Size Bytes Class Attributes
fh 1×1 32 function_handle
isempty(fh)
ans = logical
0 % Function handles are usually 1×1emptyFh = @()[]; % A handle to a function returning empty – the handle itself isn’t empty
isempty(emptyFh)
ans = logical
0
% It’s hard to create an “empty array” of function handles directly
% using standard syntax. You might get one via indexing, but
% generally, you check if a variable holds a function handle,
% not if the handle itself represents an empty array.
“`
Key Takeaway: isempty
is generally not the relevant check for function handles. You’d typically check if a variable is a function handle (isa(x, 'function_handle')
) or compare it to an empty variable if it might be unassigned (isempty(myMaybeFh)
if myMaybeFh
could be []
or a handle).
9. Objects (User-Defined Classes)
For objects of user-defined classes, isempty
behavior depends on whether the class inherits from a built-in type or defines its own isempty
method. By default, for handle classes or value classes without custom overload, isempty
checks the dimensions of the object array, just like struct arrays.
“`matlab
% Assume MyClass is defined
objArray = MyClass.empty(0, 5); % Standard way to create empty object array
isempty(objArray)
ans = logical
1obj = MyClass(); % Create a scalar object (assuming constructor allows this)
isempty(obj)
ans = logical
0 % If obj is 1×1 or similar non-zero size
“`
Key Takeaway: isempty
usually checks the object array dimensions unless the class overrides the isempty
method to provide custom logic (which is rare and generally discouraged unless there’s a very strong semantic reason).
This detailed tour shows isempty
consistently applies the dimension check across types, but awareness of how empty arrays and distinct “non-value” concepts (""
, NaN
, <missing>
) are represented in each type is crucial for correct usage.
Practical Applications and Use Cases of isempty
The theoretical understanding of isempty
is valuable, but its true power lies in its practical application to build more reliable and intelligent MATLAB programs. Here are some common scenarios where isempty
is indispensable:
1. Conditional Execution (if
, switch
)
This is perhaps the most frequent use case. You perform an action only if data exists.
“`matlab
% Example: Process data only if it’s non-empty
rawData = potentially_get_data(); % This function might return []
if ~isempty(rawData)
% Process the data
processedData = rawData * 2 + 5;
disp(‘Data processed successfully.’);
plot(processedData);
else
% Handle the case where no data was returned
disp(‘Warning: No data received. Skipping processing.’);
processedData = []; % Assign empty or default value
end
% Example: Choose different logic based on optional input
function result = myFunc(requiredArg, optionalArg)
if nargin < 2 || isempty(optionalArg)
% Use default behavior or value if optionalArg is missing or empty
disp(‘Optional argument not provided or empty. Using default.’);
optionalValue = 10;
else
disp(‘Using provided optional argument.’);
optionalValue = optionalArg;
end
result = requiredArg + optionalValue;
end
myFunc(5)
Optional argument not provided or empty. Using default.
ans =
15
myFunc(5, [])
Optional argument not provided or empty. Using default.
ans =
15
myFunc(5, 20)
Using provided optional argument.
ans =
25
“`
2. Loop Control (for
, while
)
Avoid iterating or performing actions within loops if the collection is empty. While for
loops over empty arrays naturally execute zero times, explicit checks can sometimes clarify intent or handle setup/cleanup logic. while
loops often rely on emptiness checks for termination.
“`matlab
% Example: Process files found, if any
fileList = dir(‘*.mat’); % dir returns an empty struct array if no files match
indicesToProcess = find([fileList.bytes] > 1024); % find returns [] if none found
if ~isempty(indicesToProcess)
disp([‘Processing ‘, num2str(length(indicesToProcess)), ‘ large files…’]);
for k = indicesToProcess
disp([‘ -> Processing ‘, fileList(k).name]);
% load(fileList(k).name); … process …
end
else
disp(‘No large .mat files found to process.’);
end
% Example: Process items from a queue until it’s empty
queue = {rand(3), ‘abc’, struct(‘a’,1)}; % Initialize queue
processedItems = {};
while ~isempty(queue)
currentItem = queue{1}; % Get first item
queue(1) = []; % Remove item from queue (deque)
disp('Processing item...');
% ... do something with currentItem ...
processedItems{end+1} = currentItem; %#ok<SAGROW>
end
disp(‘Queue processed.’);
“`
3. Function Input Validation
Make your functions more robust by checking if inputs are provided and non-empty when required.
“`matlab
function plotData(x, y)
% Check required inputs
if nargin < 2
error(‘plotData:NotEnoughInputs’, ‘Requires at least two input arguments (x and y).’);
end
if isempty(x) || isempty(y)
error(‘plotData:EmptyInput’, ‘Input arguments x and y cannot be empty.’);
end
if ~isnumeric(x) || ~isnumeric(y) || ~isvector(x) || ~isvector(y)
error(‘plotData:InvalidInputType’, ‘Inputs x and y must be numeric vectors.’);
end
if length(x) ~= length(y)
error(‘plotData:InputSizeMismatch’, ‘Inputs x and y must have the same length.’);
end
% --- If checks pass, proceed with function logic ---
disp('Inputs validated. Proceeding to plot.');
plot(x, y);
xlabel('X Data');
ylabel('Y Data');
title('Data Plot');
end
% Example calls
% plotData(); % Error: NotEnoughInputs
% plotData(1:5, []); % Error: EmptyInput
% plotData(1:5, ‘abc’); % Error: InvalidInputType
% plotData(1:5, 1:6); % Error: InputSizeMismatch
% plotData(1:5, (1:5).^2); % Works: Inputs validated. Proceeding to plot.
“`
4. Handling Function Outputs
Functions often return empty arrays to signal specific outcomes (e.g., “not found”, “no results satisfying criteria”). isempty
lets you interpret these outcomes correctly.
“`matlab
% Example: Find elements greater than a threshold
data = rand(1, 10);
threshold = 0.95;
highIndices = find(data > threshold); % find returns [] if none found
if isempty(highIndices)
disp(‘No data points found above the threshold.’);
else
disp([‘Found ‘, num2str(length(highIndices)), ‘ points above threshold:’]);
disp(data(highIndices));
end
% Example: Using a function that might return empty
function item = findItemByName(list, name)
item = []; % Default to empty (not found)
for k = 1:length(list)
if isfield(list(k), ‘name’) && strcmp(list(k).name, name)
item = list(k);
return; % Found, exit function
end
end
% If loop finishes without finding, item remains []
end
dataList = [struct(‘name’,’A’,’val’,1), struct(‘name’,’B’,’val’,2)];
foundItem = findItemByName(dataList, ‘B’);
if isempty(foundItem)
disp(‘Item “B” not found.’);
else
disp([‘Item “B” found with value: ‘, num2str(foundItem.val)]);
end
notFoundItem = findItemByName(dataList, ‘C’);
if isempty(notFoundItem)
disp(‘Item “C” not found.’); % This branch executes
else
disp([‘Item “C” found with value: ‘, num2str(notFoundItem.val)]);
end
“`
5. Data Cleaning and Preprocessing
Identify and potentially remove or handle empty elements/rows/columns during data preparation.
“`matlab
% Example: Remove empty rows from a cell array of strings
cellData = {‘Row1’; ”; ‘Row3’; ”; ‘Row5’};
isEmptyRow = cellfun(@isempty, cellData); % Check each cell
% Keep only non-empty rows – Method 1 (using logical indexing)
cleanData1 = cellData(~isEmptyRow);
% Keep only non-empty rows – Method 2 (using find and indexing)
% nonEmptyIndices = find(~isEmptyRow);
% cleanData2 = cellData(nonEmptyIndices);
disp(‘Original Cell Array:’);
disp(cellData);
disp(‘Cleaned Cell Array (Method 1):’);
disp(cleanData1);
% Example: Check if any column in a table is entirely missing (all
% Note: isempty doesn’t directly apply here, shows need for combination
dataTable = table([“A”;”B”;missing], [1;missing;3], [true;false;missing], …
‘VariableNames’, {‘StrCol’, ‘NumCol’, ‘LogCol’});
vars = dataTable.Properties.VariableNames;
for i = 1:width(dataTable)
% Check for MISSING values, not empty array
if all(ismissing(dataTable.(vars{i})))
disp([‘Warning: Column “‘, vars{i}, ‘” contains only missing values.’]);
end
% You might check if a column was somehow an empty array, though less common
if isempty(dataTable.(vars{i}))
disp([‘Warning: Column “‘, vars{i}, ‘” is an empty array (0 rows?).’]);
end
end
“`
6. Default Value Assignment
Provide default values for function parameters or internal variables if they are empty.
“`matlab
function configureSystem(options)
% Set default options if not provided or fields are empty
if nargin < 1 || isempty(options)
options = struct(); % Start with empty struct if completely missing
end
if ~isfield(options, 'mode') || isempty(options.mode)
options.mode = 'balanced'; % Default mode
end
if ~isfield(options, 'tolerance') || isempty(options.tolerance)
options.tolerance = 1e-6; % Default tolerance
end
if ~isfield(options, 'maxIter') || isempty(options.maxIter)
options.maxIter = 100; % Default max iterations
end
disp('Running system configuration with options:');
disp(options);
% ... use options.mode, options.tolerance, etc. ...
end
% Example calls
configureSystem(); % Uses all defaults
customOptions = struct(‘mode’, ‘fast’, ‘maxIter’, 50);
configureSystem(customOptions); % Uses provided mode/maxIter, default tolerance
partialOptions = struct(‘tolerance’, 1e-8, ‘mode’, []);
configureSystem(partialOptions); % Uses provided tolerance, default mode/maxIter
“`
7. Preventing Errors
Guard against operations that fail on empty arrays.
“`matlab
% Example: Avoid indexing errors
dataVector = get_potentially_empty_vector();
if ~isempty(dataVector)
firstElement = dataVector(1); % Safe: only access if non-empty
lastElement = dataVector(end); % Safe
disp([‘First element: ‘, num2str(firstElement)]);
disp([‘Last element: ‘, num2str(lastElement)]);
else
disp(‘Data vector is empty, cannot access elements.’);
end
% Example: Avoid mathematical operations on empty arrays
matrixA = rand(3, 4);
matrixB = get_another_matrix(); % Might return []
if isempty(matrixB)
disp(‘Matrix B is empty, cannot perform multiplication.’);
result = []; % Or handle appropriately
elseif ~isequal(size(matrixA, 2), size(matrixB, 1))
disp(‘Matrix dimensions incompatible for multiplication.’);
result = [];
else
result = matrixA * matrixB; % Safe to multiply
disp(‘Matrix multiplication performed.’);
end
“`
8. GUI Programming (App Designer, GUIDE)
Check if user input fields (like Edit Fields) are empty before processing their values.
“`matlab
% Example (Conceptual – Syntax depends on App Designer/GUIDE)
% Assuming ‘app.ValueEditField’ is an Edit Field component
inputValueStr = app.ValueEditField.Value;
if isempty(inputValueStr) % For char array input
uialert(app.UIFigure, ‘Input value cannot be empty.’, ‘Input Error’);
return; % Stop processing
end
% Or for string array input components (check for zero-length string)
inputValueStr = app.NameEditField.Value; % Assuming returns string
if strlength(inputValueStr) == 0 % Check length, not isempty
uialert(app.UIFigure, ‘Name cannot be empty.’, ‘Input Error’);
return;
end
% If valid, proceed to convert and use the input
numericValue = str2double(inputValueStr);
if isnan(numericValue)
uialert(app.UIFigure, ‘Invalid numeric input.’, ‘Input Error’);
return;
end
% … use numericValue …
“`
These examples illustrate the versatility of isempty
. It acts as a gatekeeper, directing program flow, ensuring data integrity, and preventing common runtime errors associated with unintentional operations on empty data structures.
Advanced Considerations and Edge Cases
While isempty
is generally straightforward, a few advanced points and potential edge cases are worth considering:
1. isempty(A)
vs. numel(A) == 0
The function numel(A)
returns the total number of elements in array A
(product of its dimension sizes). Therefore, if numel(A)
is 0, it implies at least one dimension must be 0, meaning A
is empty.
“`matlab
A = [];
isempty(A)
ans = logical
1
numel(A) == 0
ans = logical
1B = zeros(3, 0, 2);
isempty(B)
ans = logical
1
numel(B) == 0
ans = logical
1C = [1 2 3];
isempty(C)
ans = logical
0
numel(C) == 0
ans = logical
0
“`
In most cases, isempty(A)
and numel(A) == 0
yield the same logical result. So why prefer isempty
?
- Readability and Intent:
isempty
clearly expresses the intent to check for emptiness.numel(A) == 0
describes the condition but requires the reader to make the mental link that zero elements means empty.isempty
is more idiomatic MATLAB for this specific check. - Potential Performance: For very large arrays (that are not empty),
isempty
might be marginally faster. It only needs to check if any dimension size is zero, whilenumel
conceptually computes the product of all dimension sizes (though MATLAB’s implementation is likely optimized). For most practical purposes, the difference is negligible, butisempty
is guaranteed not to be slower. - Consistency: Using the dedicated function promotes consistency in codebases.
Recommendation: Use isempty
for checking emptiness. Use numel
when you specifically need the number of elements.
2. Multidimensional Arrays
As emphasized earlier, isempty
returns true
if any dimension has size zero.
“`matlab
A = zeros(5, 1, 3); % 5x1x3 -> Not empty
isempty(A)
ans = logical
0
numel(A)
ans =
15B = zeros(5, 0, 3); % 5x0x3 -> Empty (second dimension is 0)
isempty(B)
ans = logical
1
numel(B)
ans =
0
“`
3. Sparse Matrices
isempty
works as expected for sparse matrices, checking their dimensions.
“`matlab
S_nonempty = sparse([1, 3], [2, 4], [10, 20], 5, 5); % 5×5 sparse matrix
whos S_nonempty
Name Size Bytes Class Attributes
S_nonempty 5×5 56 double sparse
isempty(S_nonempty)
ans = logical
0S_empty_dim = sparse([], [], [], 0, 5); % 0x5 sparse matrix
whos S_empty_dim
Name Size Bytes Class Attributes
S_empty_dim 0x5 40 double sparse % Metadata takes space
isempty(S_empty_dim)
ans = logical
1
% Note: A sparse matrix can have non-zero dimensions but contain no non-zero elements.
% isempty will still be false. Use nnz() to check for non-zero elements.
S_all_zeros = sparse(3, 4); % 3×4 sparse matrix with no non-zero entries stored
isempty(S_all_zeros)
ans = logical
0 % Dimensions are 3×4, so not empty
nnz(S_all_zeros) % Number of non-zero elements
ans =
0
``
isemptychecks matrix dimensions, whereas
nnz` checks the count of stored non-zero values. These are different concepts.
4. Performance
isempty
is implemented as a highly optimized built-in function. Its execution time is typically negligible, even for large arrays, as it only needs to inspect the dimension sizes stored in the array header, not the data itself. You should generally not worry about performance bottlenecks caused by using isempty
. Checking for emptiness is almost always cheaper than potentially crashing or performing unnecessary computations on empty data.
5. Interaction with Other Validation Functions (isnumeric
, ischar
, isstruct
, etc.)
Often, you need to check both the type and emptiness. The order can matter slightly depending on your logic, but common patterns include:
“`matlab
% Pattern 1: Check type first, then emptiness (if type is correct)
if isnumeric(inputVar)
if isempty(inputVar)
disp(‘Input is an empty numeric array.’);
else
disp(‘Input is a non-empty numeric array.’);
% … process numeric data …
end
else
disp(‘Input is not numeric.’);
end
% Pattern 2: Check for non-emptiness first (short-circuiting)
if ~isempty(inputVar) && isnumeric(inputVar)
disp(‘Input is a non-empty numeric array.’);
% … process numeric data …
elseif isempty(inputVar) % Handle empty case specifically if needed
disp(‘Input is empty (type unknown or irrelevant).’);
else % It’s non-empty but not numeric
disp(‘Input is non-empty but not numeric.’);
end
% Pattern 3: Checking for optional, non-empty input of a specific type
function processOptionalNumeric(optNum)
if nargin < 1 || isempty(optNum)
disp(‘Optional numeric input not provided or empty. Using default.’);
value = 0; % Default
elseif ~isnumeric(optNum)
error(‘InvalidInput’, ‘Optional input must be numeric.’);
else
disp(‘Using provided non-empty numeric input.’);
value = optNum(1); % Example: use first element
end
% … use value …
disp([‘Processed value: ‘, num2str(value)]);
end
processOptionalNumeric();
processOptionalNumeric([]);
% processOptionalNumeric(‘abc’); % Error
processOptionalNumeric([10 20]);
“`
Choose the pattern that makes your code clearest and handles all expected cases (valid input, empty input, invalid type input).
Common Mistakes and Pitfalls
Despite its simplicity, users sometimes misuse isempty
or misunderstand its behavior, leading to bugs. Here are common pitfalls:
1. Confusing Empty Array ([]
) with Zero (0
)
- Mistake: Assuming
isempty(0)
will be true. - Why it’s wrong:
0
is a 1×1 numeric array containing the value zero. Its dimensions are non-zero. - Correct Check:
- To check for emptiness:
isempty(x)
- To check if a scalar numeric variable is zero:
x == 0
- To check if all elements of a numeric array are zero:
all(x == 0)
orall(x(:) == 0)
for multi-dimensional arrays.
- To check for emptiness:
“`matlab
x = 0;
isempty(x) % False
ans = logical
0
x == 0 % True
ans = logical
1y = [0 0; 0 0];
isempty(y) % False
ans = logical
0
all(y(:) == 0) % True
ans = logical
1
“`
2. Confusing Empty Char Array (''
) with Space (' '
) or Whitespace
- Mistake: Assuming
isempty(' ')
will be true. - Why it’s wrong:
' '
is a 1×1 character array containing the space character. Its dimensions are non-zero. - Correct Check:
- To check for an empty char array:
isempty(c)
- To check if a char array contains only whitespace characters:
all(isspace(c))
or compare after trimming:isempty(strtrim(c))
- To check for an empty char array:
“`matlab
c1 = ”;
isempty(c1) % True
ans = logical
1c2 = ‘ ‘;
isempty(c2) % False
ans = logical
0
isempty(strtrim(c2)) % True, because strtrim removes leading/trailing whitespace
ans = logical
1c3 = ‘ Hello ‘;
isempty(c3) % False
ans = logical
0
isempty(strtrim(c3)) % False, because ‘Hello’ remains after trimming
ans = logical
0
all(isspace(c3)) % False
ans = logical
0c4 = ‘ ‘; % Only whitespace
isempty(c4) % False
ans = logical
0
all(isspace(c4)) % True
ans = logical
1
isempty(strtrim(c4)) % True
ans = logical
1
“`
3. Confusing Empty String Array (strings(0,1)
) with Zero-Length String (""
)
- Mistake: Assuming
isempty("")
will be true. - Why it’s wrong:
""
creates a 1×1 string array; its dimensions are non-zero. It contains a single string element that happens to have zero characters. - Correct Check:
- To check for an empty string array:
isempty(strArr)
- To check if a scalar string has zero length:
strlength(strScalar) == 0
- To check if all strings in a string array have zero length:
all(strlength(strArr) == 0)
- To check for an empty string array:
“`matlab
s1 = strings(0,1); % Empty array
isempty(s1) % True
ans = logical
1s2 = “”; % Scalar, zero-length string
isempty(s2) % False
ans = logical
0
strlength(s2) == 0 % True
ans = logical
1s3 = [“A”, “”, “C”]; % Non-empty array containing a zero-length string
isempty(s3) % False
ans = logical
0
strlength(s3) == 0 % Element-wise: [false, true, false]
ans =
1×3 logical array
0 1 0
any(strlength(s3) == 0)% True (checks if any are zero-length)
ans = logical
1
all(strlength(s3) == 0)% False (checks if all are zero-length)
ans = logical
0
“`
4. Confusing Empty Array ([]
) with NaN
or <missing>
- Mistake: Assuming
isempty(NaN)
orisempty("<missing>")
will be true. - Why it’s wrong:
NaN
and<missing>
are specific values stored within non-empty (usually 1×1) arrays. - Correct Check:
- To check for emptiness:
isempty(x)
- To check for
NaN
values (numeric):isnan(x)
- To check for
<missing>
values (string, datetime, categorical, table elements):ismissing(x)
- To check for emptiness:
“`matlab
n = NaN;
isempty(n) % False
ans = logical
0
isnan(n) % True
ans = logical
1m_str = “
“;
isempty(m_str) % False
ans = logical
0
ismissing(m_str) % True
ans = logical
1data = [1, NaN, 3];
isempty(data) % False
ans = logical
0
isnan(data) % Element-wise: [false, true, false]
ans =
1×3 logical array
0 1 0
any(isnan(data)) % True
ans = logical
1T = table([1;2], [“A”; missing], ‘VariableNames’, {‘Num’, ‘Str’});
isempty(T) % False (Table is 2×2)
ans = logical
0
ismissing(T) % Element-wise check within table
ans =
2×2 logical array
Num Str
___ _____
0 0
0 1
any(ismissing(T), ‘all’) % Check if any element in table is missing
ans = logical
1
“`
5. Incorrectly Checking Elements Instead of the Container
- Mistake: Wanting to know if a cell array or struct array is empty, but checking one of its elements/fields instead.
- Why it’s wrong:
isempty(myCell{1})
checks if the content of the first cell is empty, not ifmyCell
itself is empty. - Correct Check: Apply
isempty
directly to the container variable (myCell
,myStructArray
).
“`matlab
myCell = {[], ‘data’}; % 1×2 cell array (not empty)
isempty(myCell) % False
ans = logical
0
isempty(myCell{1}) % True (checks the first element’s content)
ans = logical
1
“`
Avoiding these pitfalls requires a clear understanding of what isempty
checks (array dimensions) and distinguishing this from checks for specific values (0, NaN, missing, space) or properties of elements within a container (zero-length strings).
Alternatives to isempty
(and When to Use Them)
While isempty
is the standard and recommended function for checking array emptiness, other related functions or expressions exist. It’s useful to know them and understand why isempty
is usually preferred.
-
numel(A) == 0
:- Pros: Logically equivalent to
isempty(A)
. - Cons: Less idiomatic, potentially slightly less performant (negligible), doesn’t express intent as clearly.
- When to Use: Rarely needed instead of
isempty
for simply checking emptiness. Usenumel
when you need the actual count of elements.
- Pros: Logically equivalent to
-
length(A) == 0
:- Pros: Works correctly for empty vectors (
[]
,''
,{}
, etc., which have length 0). Can feel intuitive for vector-like data. - Cons: Dangerously misleading for non-vector arrays!
length(A)
returns the size of the largest dimension. A3x0
matrix haslength
3, butisempty
is true. A0x5
matrix haslength
5, butisempty
is true. - When to Use: Avoid using
length(A) == 0
as a general substitute forisempty
. Only use it if you are absolutely certain you are dealing with a variable that can only be a vector (or empty), and even then,isempty
is safer and more general.
“`matlab
A = zeros(3, 0);
isempty(A) % True (Correct)
ans = logical
1
length(A) % Returns size of largest dimension
ans =
3
length(A) == 0 % False (Incorrect check for emptiness!)
ans = logical
0
“` - Pros: Works correctly for empty vectors (
-
size(A, dim) == 0
:- Pros: Allows checking if a specific dimension is zero.
- Cons: More verbose than
isempty
for the general emptiness check. - When to Use: Use when you specifically need to know if dimension
dim
is zero, which might be different from knowing if the entire array is empty (e.g., distinguishing3x0
from0x3
).isempty
returns true for both.
“`matlab
A = zeros(3, 0);
isempty(A) % True
ans = logical
1
size(A, 1) == 0 % False (Dim 1 is 3)
ans = logical
0
size(A, 2) == 0 % True (Dim 2 is 0)
ans = logical
1
“` -
ismissing(A)
/isnan(A)
/isundefined(A)
:- Pros: Essential for detecting specific “missing” or “not-a-number” values within arrays.
- Cons: Do not check for array emptiness. An array can be non-empty but contain these values.
- When to Use: Use when you need to identify or handle these specific values, often after confirming the array is not empty using
isempty
.
-
strcmp(str, '')
orstr == ""
:- Pros: Checks if a scalar char array or string array is equal to the empty char/string value.
- Cons: Doesn’t check if the array itself is empty (e.g.,
strings(0,1)
).strcmp
only works for char arrays,== ""
only for string arrays. Fails for non-scalar arrays. - When to Use: Rarely a direct substitute for
isempty
. Can be part of logic afterisempty
, or usestrlength
for strings. For char arrays,isempty(str)
orisempty(strtrim(str))
are usually more appropriate depending on whether whitespace should count as non-empty.
In summary, while alternatives exist, isempty
remains the canonical, most reliable, and most readable way to check if a MATLAB array variable is empty across all fundamental data types. Use other functions for their specific purposes (checking dimensions, counting elements, checking for NaN/missing values).
Best Practices for Using isempty
To leverage isempty
effectively and write clean, robust MATLAB code, follow these best practices:
- Use
isempty
Idiomatically: Preferisempty(A)
overnumel(A) == 0
orlength(A) == 0
for checking array emptiness. It clearly conveys intent and avoids potential pitfalls (length
). - Understand the Definition: Remember
isempty
checks if any dimension size is zero. It does not check for values like 0, NaN, missing, space, or zero-length strings within non-empty arrays. - Validate Function Inputs: Use
isempty
(often combined withnargin
and type checks likeisnumeric
,ischar
,isstruct
) at the beginning of functions to ensure inputs are valid before proceeding. Provide informative error messages if checks fail. - Check Function Outputs: If a function you call might return an empty array to signal a specific condition (e.g.,
find
,dir
, custom functions), useisempty
to check the output and handle that condition appropriately. - Control Flow: Use
if ~isempty(A)
orif isempty(A)
to conditionally execute code blocks, preventing errors from operations on empty arrays. - Handle Optional Arguments: Use
nargin
combined withisempty
to gracefully handle optional function arguments that might be omitted or passed as[]
. - Distinguish Container vs. Content: Be clear whether you need to check if a container (like a cell array or struct array) is empty (
isempty(myCell)
) or if its contents are empty (isempty(myCell{idx})
,isempty(myStruct.field)
). - Combine Checks When Necessary: Don’t rely solely on
isempty
if you also need to exclude specific values. Combine it withisnan
,ismissing
,isspace
,strlength
, etc., as needed for comprehensive validation. For example:if ~isempty(x) && ~any(isnan(x))
- Be Mindful of
""
(String): Rememberisempty("")
isfalse
. Usestrlength(str) == 0
to check for zero-length scalar strings. - Readability: Use
~isempty(A)
which reads naturally as “if A is not empty”.
By incorporating these practices, you can harness the full potential of isempty
to make your MATLAB code significantly more reliable and easier to maintain.
Conclusion: Embracing Emptiness for Robustness
The humble isempty
function is a cornerstone of robust MATLAB programming. It provides a simple, efficient, and unambiguous way to detect empty arrays – those having at least one dimension of size zero. While the concept seems basic, understanding its precise definition and how it contrasts with other notions like zero, NaN, missing values, or zero-length strings is critical for its correct application across MATLAB’s diverse data types.
We have explored its syntax, its behavior with numeric, character, string, cell, structure, table, and other arrays, and highlighted crucial distinctions. We delved into numerous practical use cases, demonstrating how isempty
is essential for input validation, controlling program flow, handling function outputs, preventing errors, and assigning default values. We also considered alternatives, common pitfalls, and advanced considerations like performance and interaction with other functions.
Mastering isempty
is not just about learning a single function; it’s about adopting a defensive programming mindset. By anticipating and gracefully handling potential emptiness in your data, you prevent unexpected errors, create more resilient applications, and write code that is clearer and easier for others (and your future self) to understand. Make isempty
a standard part of your MATLAB toolkit, use it idiomatically, and embrace the check for emptiness as a fundamental step towards writing high-quality, professional MATLAB code.