MATLAB - Tables
MATLAB - Modern Data Handling with Tables
Section titled “MATLAB - Modern Data Handling with Tables”In modern data analysis, data is rarely uniform. You often work with datasets containing a mix of text, numbers, and dates. MATLAB’s table data structure is specifically designed for this purpose. A table is a container that stores columns of data, where each column can have a different data type but all columns must have the same number of rows.
Tables are a cornerstone of the modern MATLAB workflow, providing an intuitive, flexible, and efficient way to organize, clean, and analyze tabular data, similar to a spreadsheet or a database table.
Tables vs. Matrices: The Key Difference
Section titled “Tables vs. Matrices: The Key Difference”Understanding when to use a table versus a traditional matrix is crucial.
| Feature | Matrices | Tables |
|---|---|---|
| Data Type | Homogeneous: All elements must be the same type (e.g., double). | Heterogeneous: Each column can have a different type (e.g., string, double, datetime). |
| Data Access | Numeric indexing: A(row, col). Relies on remembering numeric positions. | Named indexing: T.VariableName or T(:, 'VariableName'). Code is more readable and robust. |
| Metadata | No built-in support for metadata like column names or row identifiers. | Built-in properties for variable (column) names, row names, and descriptions. |
| Use Case | Linear algebra, mathematical computations, image processing. | Data analysis, importing mixed-type data from files (CSV, Excel), statistical modeling. |
Creating a MATLAB Table
Section titled “Creating a MATLAB Table”The table() function is the primary way to create tables. You can create them from existing workspace variables or pre-allocate them for future data.
Syntax
Section titled “Syntax”% Create from existing column vectorsT = table(col1, col2, ..., colN);
% Create and specify variable namesT = table(col1, col2, 'VariableNames', {'name1', 'name2'});
% Pre-allocate a tableT = table('Size', [numRows, numCols], 'VariableTypes', {'type1', 'type2', ...});Example 1: Creating a Simple Patient Data Table
Section titled “Example 1: Creating a Simple Patient Data Table”Let’s create a table from separate arrays. Note the use of modern string arrays for names, which are more flexible than cell arrays of characters.
% 1. Define column dataLastName = ["Smith"; "Jones"; "Williams"; "Brown"]; % Modern string arrayAge = [38; 43; 38; 40];IsSmoker = [true; false; true; false];Height = [71; 69; 64; 67];
% 2. Create the table% MATLAB automatically uses the variable names for the column headerspatientData = table(LastName, Age, IsSmoker, Height)When executed, MATLAB displays a clean, formatted table:
patientData =
4x4 table
LastName Age IsSmoker Height ___________ ___ ________ ______
"Smith" 38 true 71 "Jones" 43 false 69 "Williams" 38 true 64 "Brown" 40 false 67Example 2: Pre-allocating and Populating a Table
Section titled “Example 2: Pre-allocating and Populating a Table”Pre-allocation is efficient when you know the final size of your data but will be collecting it in a loop.
% Define table structurenumRows = 5;varTypes = {'string', 'double', 'datetime'};varNames = {'SensorID', 'Reading', 'Timestamp'};
% Pre-allocate the tablesensorLog = table('Size', [numRows, numel(varTypes)], ... 'VariableTypes', varTypes, ... 'VariableNames', varNames);
% Populate the table (e.g., in a loop)for i = 1:numRows sensorLog.SensorID(i) = "Sensor_" + i; sensorLog.Reading(i) = rand() * 100; sensorLog.Timestamp(i) = datetime('now') + days(i);end
disp(sensorLog);Accessing and Modifying Table Data
Section titled “Accessing and Modifying Table Data”Modern MATLAB uses intuitive dot notation for most table operations, making your code clean and easy to read.
Let’s use the patientData table from our first example.
% Access a single column (returns a vector)ages = patientData.Age;
% Access a single element from that columnfirstPatientAge = ages(1); % Returns 38
% --- Direct Access ---
% Access a specific element using dot notation and row indexfirstPatientAge_direct = patientData.Age(1); % Returns 38
% Access multiple columns (returns a new, smaller table)personalInfo = patientData(:, {'LastName', 'Age'});
% Access rows using numeric indexing or logical indexingallSmokers = patientData(patientData.IsSmoker, :);
% --- Modifying Data ---
% Modify a single valuepatientData.Age(2) = 44; % Update Jones's age
% Add a new columnpatientData.Weight = [176; 163; 131; 155];disp(patientData);Working with Row Names
Section titled “Working with Row Names”Just like column names, you can assign unique row names for easy lookups.
% Use the patient's last name as a unique row identifierpatientData.Properties.RowNames = patientData.LastName;
% Now you can access data by row name% Note the use of curly braces {} for character vectors and () for tablessmithsData_table = patientData('Smith', :); % Returns a 1-row table
williamsAge = patientData{'Williams', 'Age'}; % Returns the scalar value 38Practical Tips and Best Practices
Section titled “Practical Tips and Best Practices”- Get a Quick Overview: Use
summary(T)to get a statistical summary of each variable in the table. It’s great for an initial data exploration. - Handling Missing Data: Tables have built-in support for missing values (e.g.,
NaNfor numbers,<missing>for strings). Functions likeismissingandfillmissingare designed to work seamlessly with tables. - Performance: For very large datasets, pre-allocating tables is significantly faster than growing them inside a loop.
- Readability: Always use dot notation (
T.VariableName) when accessing single columns. It’s faster and makes your code’s intent much clearer thanT(:, 'VariableName').