In MATLAB, cell arrays are a type of arrays which stores elements of different data types and sizes in different cells, or one could say that cell arrays allow users to store heterogeneous data into a single array. For example, let us create a cell array which holds the name and age of a person.
Example 1:
Matlab
arr = { "Harry" , "Stark" , 23}
|
Output:
This will create a cell array of 1×3:
This was a simple example of cell arrays but, this is not a feasible way of creating them. So, we will now see better and efficient ways of creating and accessing the elements within.
Creating Empty Cell Arrays:
The cell() function creates an empty cell array of desired size. Its syntax is
arr_name = cell (<size>);
Let us see some examples, this will create a cell array of size x size dimensions.
Example 2:
Output:
Example 3:
Creating a cell array of size, size1 x size2 x … x sizeN.
Output:
The resultant cell array would be of (3×2)x3 size.
Accessing Elements of Cell Arrays:
The elements of a cell array can be accessed by the same method of accessing ordinary arrays, by the indexing method. Let us see this with the help of an example.
Example 4:
Matlab
arr = {
[ "Harry" , "Stark" ];
2:9;
linspace(1,2,5)
};
arr(1)
arr(2)
arr(3)
|
Output: