【Basics】MATLAB Cell Arrays
发布时间: 2024-09-13 15:49:21 阅读量: 14 订阅数: 25
# 2.1 Creating and Initializing Cell Arrays
Cell arrays can be created in the following ways:
```
% Creating a cell array using curly braces
cell_array = {'string', 1, [2, 3], struct('name', 'John')};
% Creating a cell array using the cell function
cell_array = cell(3, 2); % Creates a 3x2 cell array, elements initialized as {}
% Converting a numeric array to a cell array using num2cell function
num_array = [1, 2, 3];
cell_array = num2cell(num_array);
```
# 2. Cell Arrays: Creation and Operations
### 2.1 Creating and Initializing Cell Arrays
Cell arrays can be created and initialized in various ways. The simplest method is to use curly braces {}, with each element separated by commas. For example:
```matlab
myCellArray = {'Hello', 'World', 1, 2.5, true};
```
This code creates a cell array with five elements, with the types being string, string, number, floating-point number, and boolean, respectively.
### 2.2 Indexing and Accessing Cell Array Elements
Elements of a cell array can be accessed using square brackets [] and indices. The indexing starts at 1, indicating the first element. For example:
```matlab
myCellArray{1} % Outputs: 'Hello'
myCellArray{3} % Outputs: 1
```
Multiple elements can also be accessed using the colon operator :. For example:
```matlab
myCellArray{1:3} % Outputs: {'Hello', 'World', 1}
```
### 2.3 Merging and Splitting Cell Arrays
Cell arrays can be merged using the [] operator. For example:
```matlab
cellArray1 = {'Hello', 'World'};
cellArray2 = {1, 2.5, true};
mergedCellArray = [cellArray1, cellArray2];
```
This code creates a new cell array with five elements, where the first two elements are from cellArray1 and the last three from cellArray2.
Cell arrays can be split using the horzcat() and vertcat() functions. The horzcat() function horizontally concatenates cell arrays, while the vertcat() function vertically concatenates cell arrays. For example:
```matlab
cellArray1 = {'Hello', 'World'};
cellArray2 = {1, 2.5, true};
horizontalCellArray = horzcat(cellArray1, cellArray2);
verticalCellArray = vertcat(cellArray1, cellArray2);
```
horizontalCellArray will contain five elements, where the first two are from cellArray1 and the last three from cellArray2. verticalCellArray will contain seven elements, where the first two are from cellArray1 and the last five from cellArray2.
# 3. Data Types and Conversions of Cell Arrays
### 3.1 Storing
0
0