Matlab

How To Add Single Element to an Array or Vector in MATLAB

Adding a single element to an array or vector is a common operation in MATLAB. Whether you’re working with large datasets or manipulating arrays for mathematical computations, it’s essential to know efficient methods to perform this task.

How To Add a Single Element to an Array or Vector in MATLAB

Adding a single element to an array can be used to update the array, insert a new element into the array, or extend the array, here are some ways for it:

1: Using Indexing
The most straightforward way to add an element to an array or vector is by indexing. MATLAB allows the direct assignment of a value to a specific index, expanding the array if necessary. For example:

A = [1, 2, 3, 4];  
disp("Original Array:");
disp(A);

A(5) = 5;  
disp("Array after adding element at index 5:");
disp(A);

Output

2: Using Concatenation
Concatenation is another method to add a single element to an array or vector. By using square brackets, you can combine existing array elements with the new element. Here’s an example:

A = [1, 2, 3, 4];  
disp("Original Array:");
disp(A);
newElement = 5;
A = [A, newElement];  
disp("updated Array:");
disp(A);

Output

3: Using the cat Function
The cat() function in MATLAB allows concatenation along a specified dimension. To add an element using this method, we concatenate the original array with the new element along the desired dimension. For a row vector, we use dimension 2 and for a column vector set the dimension 1:

A = [1, 2, 3, 4];
disp("Original Array:");
disp(A);
newElement = 5;
A = cat(2, A, newElement);  
disp("Updated Array:");
disp(A);

Output

4: Using vertcat or horzcat Functions
The vertcat() and horzcat() functions provide convenient ways to concatenate arrays vertically or horizontally. By using these functions, we can easily add a single element to an array or vector. Here’s an example using horzcat():

Output

Conclusion

Adding a single element to an array or vector in MATLAB is a common task with several efficient techniques available. By using indexing, concatenation, cat, or vercat/horzcat functions you can accomplish this task effectively.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.