4.2. Matrix Creation and Concatenation
Table of Contents
Introduction
In MATLAB, matrices are at the center of almost everything you do. In this chapter you focus on how to create matrices of different shapes and how to join smaller pieces together into larger ones. You build on the basic idea of vectors and arrays, but stay focused on what is specific to matrix creation and concatenation.
Creating Matrices with Literal Notation
The most direct way to create a matrix is to type it explicitly using square brackets. Inside the brackets, you separate elements in a row by spaces or commas, and you separate rows by semicolons.
For example, a 2-by-3 matrix can be written as
A = [1 2 3; 4 5 6];This creates
$$
A =
\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{bmatrix}
$$
The same matrix can also be created with commas between entries in a row:
A = [1, 2, 3; 4, 5, 6];Spaces and commas serve the same purpose within a row. Semicolons always end the current row and start a new one.
You can include expressions inside the brackets. MATLAB evaluates the expressions first and then arranges the results into the matrix shape you specified.
B = [1+1 2*3; 10/5 sqrt(16)];Every row must have the same number of elements. If one row has more or fewer entries than another, MATLAB will give an error at creation time.
Mixing Row and Column Vectors into Matrices
You can combine existing row and column vectors to form matrices as long as the dimensions line up.
Suppose you have
r = [1 2 3]; % 1-by-3 row vector
c = [4; 5; 6]; % 3-by-1 column vectorYou can create a 2-by-3 matrix by stacking row vectors:
A = [r; r+10];
Here r is the first row, and r+10 is the second row. The result is
$$
A =
\begin{bmatrix}
1 & 2 & 3 \\
11 & 12 & 13
\end{bmatrix}
$$
You can also form a 3-by-2 matrix by placing column vectors side by side:
B = [c, 2*c];
The first column is c. The second column is 2*c. The result is
$$
B =
\begin{bmatrix}
4 & 8 \\
5 & 10 \\
6 & 12
\end{bmatrix}
$$
The important requirement is that all rows have the same length, and all columns have the same height.
Creating Matrices with Functions
Typing out every element is often inconvenient. MATLAB provides functions that create common matrix shapes quickly.
A matrix of zeros with a specific size can be created with zeros. For example
Z = zeros(3, 4);
creates a 3-by-4 matrix where every entry is 0.
Similarly, ones creates a matrix of ones:
O = ones(2, 5);
This gives a 2-by-5 matrix of 1s.
To create an identity matrix, where the diagonal entries are 1 and the others are 0, use eye. For example
I = eye(4);creates a 4-by-4 identity matrix.
You can also use size information from another matrix to create new ones with matching dimensions:
A = [1 2 3; 4 5 6];
Zsame = zeros(size(A));
Here Zsame is a 2-by-3 matrix of zeros, with the same size as A.
Concatenation Basics
Concatenation means joining arrays together to make a larger array. In MATLAB, you concatenate by writing arrays inside one pair of square brackets. The position inside the brackets determines how they are joined.
You use spaces or commas between arrays to place them side by side horizontally. You use semicolons between arrays to stack them vertically.
For example, if
A = [1 2; 3 4]; % 2-by-2
B = [5 6; 7 8]; % 2-by-2
You can create a 2-by-4 matrix by putting A and B next to each other:
H = [A B];or
H = [A, B];The result is
$$
H =
\begin{bmatrix}
1 & 2 & 5 & 6 \\
3 & 4 & 7 & 8
\end{bmatrix}
$$
You can also stack A on top of B to make a 4-by-2 matrix:
V = [A; B];which yields
$$
V =
\begin{bmatrix}
1 & 2 \\
3 & 4 \\
5 & 6 \\
7 & 8
\end{bmatrix}
$$
The direction of concatenation is completely determined by the separators you use inside the brackets.
Dimension Rules for Concatenation
When you concatenate, the dimensions must be compatible. For horizontal concatenation, all matrices must have the same number of rows. For vertical concatenation, they must have the same number of columns.
If
A = [1 2; 3 4]; % 2-by-2
c = [10; 20]; % 2-by-1
then [A c] is valid because both A and c have 2 rows. The result is a 2-by-3 matrix. However, [A; c] will produce an error because vertically stacking requires the same number of columns, and A has 2 columns while c has 1.
Similarly, if
r = [7 8 9]; % 1-by-3
then [r; A] is invalid, because r has 3 columns while A has 2.
When MATLAB reports a concatenation error, it usually means one of the sizes does not match. It is often helpful to check sizes with size before attempting to concatenate.
Concatenating Scalars, Vectors, and Matrices Together
Scalars, row vectors, column vectors, and matrices can all be mixed during concatenation, as long as the dimension rules are respected.
For instance, you can build a matrix that combines scalars and row vectors:
r1 = [2 3 4];
r2 = [5 6 7];
A = [1 r1; 0 r2];
Here, 1 and 0 are treated as 1-by-1 matrices. MATLAB expands the first row to [1 2 3 4] and the second row to [0 5 6 7]. The final result is a 2-by-4 matrix.
You can also construct block matrices from smaller matrices, which is very common in linear algebra. For example, if A and B are both 2-by-2, you can build a 4-by-4 matrix:
C = [A B; B A];
Here, the top row of blocks is [A B], and the bottom row of blocks is [B A]. The semicolon between them stacks these block rows vertically.
Growing Matrices Incrementally
MATLAB allows you to build a matrix by assigning to parts of it using indexing. This is a form of concatenation where you expand the matrix over time. For example
M = [];
M = [M 1]; % now 1-by-1
M = [M 2 3]; % now 1-by-3You can also expand in two dimensions:
A = [];
A(1, 1) = 10;
A(2, 3) = 20;
After these assignments, MATLAB has filled missing values with zeros, and A is a 2-by-3 matrix. Although this is convenient for interactive work and quick experiments, expanding arrays in many small steps is usually slower than allocating the full size first and then filling it. Performance considerations are discussed in more detail elsewhere, but it is useful to know that this style of incremental growth is allowed.
Using `cat` for General Concatenation
In addition to bracket notation, MATLAB offers the cat function for concatenating along a specified dimension. This is particularly useful when you work with more than two dimensions, but it can also be used with 2D matrices.
The syntax is
C = cat(dim, A, B, ...);
The argument dim is the dimension along which to join the arrays.
For 2D matrices, dim = 1 corresponds to vertical concatenation and dim = 2 corresponds to horizontal concatenation.
For example
A = [1 2; 3 4];
B = [5 6; 7 8];
V = cat(1, A, B); % vertical, same as [A; B]
H = cat(2, A, B); % horizontal, same as [A B]
All arrays passed to cat must have the same size in every dimension except the one you are joining along.
Concatenation with Empty Arrays
Empty arrays have size zero in at least one dimension. An empty row vector has size 1-by-0, and an empty column vector has size 0-by-1. Sometimes it is useful to concatenate with empty arrays, especially when you initialize containers.
For example
A = [];
A = [A 1 2 3];
results in A being a 1-by-3 matrix. Concatenating nothing with something simply gives you the nonempty part, as long as the empty array has a compatible shape.
On the other hand, attempting to concatenate arrays that have conflicting dimensions, even if one dimension is zero, will still produce an error. The usual size matching rules still apply.
Practical Patterns of Matrix Creation
Several common patterns appear frequently when creating and concatenating matrices.
One typical pattern is to build a matrix of samples, where each column represents a sample vector. For example, if you have three 3-by-1 sample vectors x1, x2, x3, you might write
X = [x1 x2 x3];to form a single 3-by-3 matrix, where each column is one sample.
Another pattern is to form augmented matrices used in basic linear algebra, such as writing $\left[ A \,|\, b \right]$ to solve a system. In MATLAB, with a matrix A and column vector b of compatible size, you can write
Aug = [A b];This creates a matrix that contains both the coefficient matrix and the right hand side vector.
These patterns rely on the same basic ideas: use brackets to join pieces, make sure the sizes line up correctly, and think in terms of rows and columns.
Important points to remember:
Square brackets [] create matrices directly, with spaces or commas between columns and semicolons between rows.
All rows in a matrix must have the same number of elements, and all columns must have the same number of elements.
Horizontal concatenation uses spaces or commas, vertical concatenation uses semicolons, and dimensions must match appropriately.
Functions like zeros, ones, and eye quickly create common matrix shapes without typing every element.
The cat function concatenates arrays along a chosen dimension and is useful when working with more than two dimensions.
Growing matrices step by step with concatenation or indexing is allowed but may be slower than preallocating the final size.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!