Another exciting type of array in MATLAB is a cell array! Cell arrays can be defined in 1 or 2 dimensions and hold some handy features. Remember back to when we defined mixed variable types within arrays and matrices? We ran into some conflicts between the types that caused errors or gave unexpected outcomes. Well, with cell arrays, we can add variables of different types to a cell array; we can even add matrices and arrays inside of cell arrays!
Let's start off by creating some cell arrays.
matlab
cell1 = {"hi", 5, 'character', true};
cell2 = {4 2 9};
Notice how both cell arrays have been defined and none of the variable types have been changed. This is because MATLAB treats each cell value as its own "space" per se rather than trying to convert everything to read the same way like in matrices and arrays. I mentioned we can also define more complex cell arrays by defining arrays and matrices inside of cell arrays. Let's try it!
matlab
cell3 = { "hello", [2,7;8,9], {'character'}};
We can also nest cell arrays inside of one another for even more complex structures.
Changing cell arrays is slightly different when compared to matrices and arrays because we have a nested index, and cell arrays using curly braces rather than parenthesis for indexing. Let's change a value inside of cell3 to test. We are going to change the value in the second row, first column of the matrix in cell3; let's do it.
matlab
% from before
cell3 = { "hello", [2,7;8,9], {'character'}};
cell3{2}(2,1) = 0
% output: { "hello", [2,7;0,9], {'character'}};
What we did was we first targeted the second index of cell3 to get to the matrix; this was done by typing cell3{2}. Then, we accessed the matrix like normal to change the value in the second row, first column by typing cell3{2}(2,1).