Matlab

How to Append an Element to an Array in MATLAB

When working with data in MATLAB, the ability to append or add elements to an existing array is crucial. Appending allows you to expand the size of an array and accommodate additional data points. Whether you are dealing with dynamic datasets or need to update your array with new information, mastering the art of array appending.

This blog will explore how to append a number or an element in an array.

Appending an Element in an Array?

An element can be appended to an array using square brackets [] or horzcat() method. We can append an element vertically or horizontally to an array. This method can create a new array from the existing one. We can add one or more components to an existing array by putting them outside of the existing row and column index bounds, to maintain the array’s rectangular shape, MATLAB automatically adds zero padding.

Examples

Let’s consider examples demonstrating how to vertically or horizontally append an element to an array vertically or horizontally.

Example 1

In this example, we first create an array and then append element 7 at the 4th index.

x = [3 5 8];
x = [x,7]

Example 2

This MATLAB code appends element 7 at the 4th index using the MATLAB horzcat() method.

x = [3 5 8];
x = horzcat(x,7)

Example 3

Using the given MATLAB code, we first initialize a 2-dimensional array having 3 rows and 3 columns. After that, we append an element at the index (4,2). The resultant array will have a new row appending element 9 horizontally at the location (4,2).

A = eye(3)
A(4,2) = 9

Example 4

In this MATLAB code, we first create a 3-dimensional array having 3 rows, 2 columns, and 2 sheets. After that, we append an element at the index (3,3,2). The resultant array will have a new column appending element 9 vertically at the location (3,3,2).

A = rand(3,2,2)
A(3,3,2) = 9

The screenshot given below displays the existing array having dimensions (3,2,2).

The given screenshot displays a new resultant array after appending element 9 having dimensions (3,3,2).

Conclusion

A list of numbers arranged in columns and rows is known as an array. An element or a number can be appended to a display using square brackets []. We can append an element vertically or horizontally to an array. This method can create a new array from the existing one. We can add one or more components to an existing array by putting them outside of the existing row and column index bounds, to maintain the array’s rectangular shape, MATLAB automatically adds zero padding. This tutorial explored how to append an element horizontally or vertically to an array.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.