Written and maintained by CASRAI Editorial Board
Published
On this page
In MATLAB, appending data encompasses two distinct operational requirements depending on the underlying data type: combining text using the built-in append function, or joining numeric matrices, cell arrays, and data tables using bracket concatenation operators ([]), vertcat, and horzcat. Understanding how to properly append in MATLAB and append MATLAB arrays ensures robust data ingestion, avoids silent text truncation bugs, and eliminates severe memory reallocation penalties during large-scale simulations and data analysis pipelines.
What it is used for in research
Scientific data processing routinely requires combining incremental experimental measurements, batch trial logs, and multi-file text corpora into unified structures for statistical modeling and visualization. In scientific computing in MATLAB, appending operations appear in several core research scenarios:
- Automating file paths and identifiers: Researchers generating batch filenames or export directories use text appending to join subject IDs, experimental conditions, timestamps, and file extensions into standardized strings.
- Combining experimental trial runs: Laboratory equipment often streams numeric data per trial or epoch. Appending new measurement vectors to an ongoing matrix allows real-time session tracking.
- Aggregating longitudinal datasets: Research surveys and longitudinal observation tables require appending participant rows across recruitment cohorts into a master MATLAB data table.
- Persistent incremental storage: When running multi-day numerical simulations, researchers periodically append checkpoint variables to disk by saving MAT-files with the append flag without overwriting existing workspace variables.
Install or access (official source only)
MATLAB is commercial technical computing software developed by MathWorks. To access MATLAB and run append operations:
- Official portal: Access software downloads, license activations, and system requirements directly through the official MathWorks website (
https://www.mathworks.com). - Institutional access: Most research universities provide campus-wide site licenses accessible via an institutional MathWorks Account login.
- Browser-based access: MATLAB Online (
https://matlab.mathworks.com) enables full script execution and file management directly within modern web browsers without local installation. - Version requirements: The dedicated
appendstring function was introduced in MATLAB R2020b and is included in all subsequent releases. Bracket-based matrix concatenation ([],vertcat,horzcat,cat) is a core foundational feature available in all MATLAB versions. No specialized toolboxes are required.
Step-by-step task
The following numbered procedures detail how to append strings, numeric vectors, matrices, tables, and cell arrays in MATLAB using current official syntax.
1. Appending strings with the append function
Introduced in MATLAB R2020b, the append function joins text elements from multiple string arrays, character vectors, or cell arrays of character vectors. Crucially, MathWorks documentation recommends append over legacy strcat because append preserves trailing whitespace across all input types.
% Combine string scalars
sampleID = "Subject_042";
condition = " Treatment_B ";
suffix = ".mat";
filename = append(sampleID, condition, suffix);
% Result: "Subject_042 Treatment_B .mat"
% Combine character vectors while preserving trailing spaces
prefix = 'Trial_';
val = '01 ';
status = 'PASS';
fullStr = append(prefix, val, status);
% Result: 'Trial_01 PASS'
The append function also supports element-wise vectorized concatenation across arrays of compatible dimensions:
stems = ["sensor_A"; "sensor_B"];
suffixes = ["_raw"; "_calibrated"];
channels = append(stems, suffixes);
% Returns 2x1 string array:
% "sensor_A_raw"
% "sensor_B_calibrated"
2. Appending elements and vectors with bracket concatenation
To append elements to numeric vectors, MATLAB uses square brackets ([]). Commas or spaces append elements horizontally (increasing columns), while semicolons append vertically (increasing rows):
% Appending to a row vector (horizontal)
v = [10, 20, 30];
v = [v, 40];
% Result: [10, 20, 30, 40]
% Appending to a column vector (vertical)
col = [1; 2; 3];
col = [col; 4];
% Result: [1; 2; 3; 4]
3. Appending rows and columns to matrices with vertcat and horzcat
When appending to 2D matrices, MATLAB enforces strict dimension compatibility. To append a new row vertically, use a semicolon or explicit vertcat; the number of columns in the appended row must match the existing matrix. To append a new column horizontally, use a comma, space, or explicit horzcat; the number of rows must match.
% Existing 2x3 experimental data matrix
M = [1.2, 3.4, 5.6;
7.8, 9.0, 2.1];
% Append a 1x3 row to the bottom (vertical concatenation)
newRow = [4.5, 6.7, 8.9];
M_extended_rows = [M; newRow]; % Equivalent to vertcat(M, newRow)
% Append a 2x1 column to the right (horizontal concatenation)
newCol = [10.5; 11.2];
M_extended_cols = [M, newCol]; % Equivalent to horzcat(M, newCol)
When multi-dimensional blocks require repeating or matching shapes before concatenation, researchers combine these operations with MATLAB repmat array tiling.
4. Appending rows and variables to MATLAB data tables
Tabular data structures require matching variable names and data types when appending rows:
% Existing experimental table
T1 = table([101; 102], ["Placebo"; "Drug_A"], [12.4; 15.1], ...
'VariableNames', {'SubjectID', 'Cohort', 'Baseline'});
% New experimental observation (must share identical VariableNames)
newObservation = table(103, "Drug_B", 14.8, ...
'VariableNames', {'SubjectID', 'Cohort', 'Baseline'});
% Append rows vertically
T_combined = [T1; newObservation]; % Equivalent to vertcat(T1, newObservation)
% Append a new column / variable directly by assignment
T_combined.PostTreatment = [11.8; 9.4; 10.2];
5. Appending data to cell arrays
For heterogeneous data types (such as combining strings, numeric arrays of differing dimensions, and metadata structures), cell arrays provide flexible indexing via curly braces ({}):
% Initialize cell array
experimentData = {'Trial_A', [1, 2, 3]};
% Append a new element to the end using dynamic index end+1
experimentData{end+1} = [4, 5, 6, 7];
% Append a new metadata struct element
experimentData{end+1} = struct('Operator', 'Tech_1', 'Temp', 22.5);
6. Preallocating arrays instead of dynamic loop growth
In iterative algorithms such as loops in MATLAB, appending elements dynamically at every iteration (e.g., v = [v, x] or A(end+1) = x) causes severe performance degradation. MATLAB is forced to request a new contiguous block of memory from the operating system and copy all previous elements on every iteration, leading to $O(N^2)$ computational complexity.
% INEFFICIENT: Dynamic appending inside a loop (reallocates memory every iteration)
data = [];
for i = 1:50000
data = [data, sqrt(i)]; % Notice MATLAB Editor warning: 'variable appears to change size'
end
% OPTIMAL: Preallocate contiguous memory buffer using zeros
N = 50000;
data = zeros(1, N); % Preallocated memory block
for i = 1:N
data(i) = sqrt(i);
end
Output and how to read it
When running append operations in the MATLAB Command Window, MATLAB displays outputs reflecting the underlying data container and dimension attributes:
- Strings vs Character Vectors: Text joined with
appenddisplays enclosed in double quotation marks if any argument is a string (e.g.,"Subject_042 Treatment_B .mat"), indicating a MATLABstringarray. If all arguments are single-quoted character arrays, the output displays with single quotes (e.g.,'Trial_01 PASS'). - Matrix Dimensions: Use the
sizecommand to confirm successful concatenation. For instance, executingsize(M_extended_rows)after vertically concatenating a 1×3 row to a 2×3 matrix returns[3, 3]. - Workspace Inspection: Executing
whosin the Command Window prints a structured summary displaying variable names, array sizes, byte sizes, and classes (such asdouble,string,table, orcell). Inspectingwhosconfirms that data types have not unintentionally been cast to a less specific format during concatenation.
Troubleshooting
The following diagnostics address common errors encountered when attempting to append in MATLAB:
- Error: “Dimensions of arrays being concatenated are not consistent.”
Cause: Attempting vertical concatenation (
[A; B]) when arrays possess differing numbers of columns, or horizontal concatenation ([A, B]) when arrays possess differing numbers of rows.Fix: Verify array shapes using
size(A)andsize(B). If concatenating column vectors horizontally or row vectors vertically, transpose one operand using the single-quote operator (v') to match dimensions. - Silent text bug: Trailing whitespace stripped by strcat
Cause: Legacy scripts using
strcat('prefix ', 'suffix')lose trailing spaces becausestrcatautomatically strips trailing whitespace from character vector arguments, producing'prefixsuffix'.Fix: Replace
strcatwith the modernappendfunction:append('prefix ', 'suffix')preserves all trailing spaces exactly as defined. - Severe loop execution slowdown
Cause: Using
arr = [arr, val]orarr(end+1) = valinside extensivefororwhileloops.Fix: Preallocate arrays using
zeros(rows, cols)for numeric data,strings(rows, cols)for text, orcell(rows, cols)for heterogeneous structures before entering the loop. - Error: “Variable names in the tables being concatenated must match.”
Cause: Attempting
[T1; T2]when table column headers differ in spelling, capitalization, or column order.Fix: Ensure consistent column names prior to concatenation by assigning
T2.Properties.VariableNames = T1.Properties.VariableNamesor using thejoin/outerjoinfunctions for relational merges.
Free alternatives (table)
Researchers seeking open-source tools with similar array and text concatenation capabilities can evaluate several free alternatives:
| Software | Append / Concatenation Syntax | Key Strengths in Research | License |
|---|---|---|---|
| GNU Octave | [A, B], [A; B], horzcat(), vertcat(), [str1, str2] |
Near-identical syntax to MATLAB; seamless script migration for matrix manipulation. | GPLv3 |
| Python (NumPy) | np.append(A, B, axis=0), np.concatenate([A, B]), list .append() |
Universal data science ecosystem; extensive scientific libraries (SciPy, pandas, PyTorch). | BSD / PSF |
| Julia | [A; B], [A B], vcat(A, B), hcat(A, B), push!(arr, x) |
High-performance just-in-time (JIT) compilation; native multiple dispatch; fast array operations. | MIT |
| Scilab | [A, B], [A; B], cat() |
Dedicated numerical engineering package with Xcos block simulation diagrams. | CeCILL (GPL compatible) |
FAQ
How do you append in MATLAB?
How you append in MATLAB depends on whether you are working with text or numeric data. For text and string arrays, use the modern append(str1, str2, ..., strN) function introduced in MATLAB R2020b. For numeric vectors and matrices, use bracket concatenation: [A, B] or horzcat(A, B) appends horizontally (adding columns), while [A; B] or vertcat(A, B) appends vertically (adding rows). For cell arrays, append new elements using dynamic indexing: C{end+1} = newElement.
What is the difference between append and strcat in MATLAB?
The primary difference lies in whitespace handling. The legacy strcat function automatically strips trailing ASCII whitespace from character vector inputs, which frequently creates unintended errors when building formatted text or file paths. In contrast, append preserves all whitespace characters across character vectors, string arrays, and cell arrays. Furthermore, append offers robust vectorization and handles mixed text inputs more predictably.
How do you append a row to a matrix in MATLAB?
To append a row to an existing matrix M, use vertical bracket concatenation with a semicolon: M = [M; newRow], or call vertcat(M, newRow). The appended row must be a row vector containing exactly the same number of columns as M; otherwise, MATLAB throws a dimension mismatch error.
Why is appending to an array inside a for loop slow in MATLAB?
Appending elements dynamically inside a loop with syntax such as v = [v, x] forces MATLAB to reallocate memory and copy all existing elements to a new contiguous memory location on every iteration. This turns an $O(N)$ linear loop into an $O(N^2)$ quadratic operation. To achieve optimal performance, preallocate the entire array using zeros(1, N) before the loop and assign values by direct index (v(i) = x).
Can you append variables to an existing MAT-file?
Yes. To add or update variables in an existing MAT-file on disk without overwriting other saved variables, use the -append flag with the save command: save('experiment_results.mat', 'newVariable', '-append').
Sources (official docs)
- MathWorks (2026-11-09). append: Combine strings or character vectors. MathWorks Help Center. https://www.mathworks.com/help/matlab/ref/append.html
- MathWorks (2026-11-09). vertcat: Concatenate arrays vertically. MathWorks Help Center. https://www.mathworks.com/help/matlab/ref/vertcat.html
- MathWorks (2026-11-09). horzcat: Concatenate arrays horizontally. MathWorks Help Center. https://www.mathworks.com/help/matlab/ref/horzcat.html
- MathWorks (2026-11-09). Preallocating Arrays. MathWorks Help Center. https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
- Free Software Foundation / GNU Octave (2026-11-09). Rearranging Matrices and Concatenating Strings. GNU Octave Official Documentation. https://docs.octave.org/latest/Rearranging-Matrices.html







