Elements of the same class can often be concatenated into arrays (with a few rare exceptions, e.g. function handles). Numeric scalars, by default of class double
, can be stored in a matrix.
>> A = [1, -2, 3.14, 4/5, 5^6; pi, inf, 7/0, nan, log(0)]
A =
1.0e+04 *
0.0001 -0.0002 0.0003 0.0001 1.5625
0.0003 Inf Inf NaN -Inf
Characters, which are of class char
in MATLAB, can also be stored in array using similar syntax. Such an array is similar to a string in many other programming languages.
>> s = ['MATLAB ','is ','fun']
s =
MATLAB is fun
Note that despite both of them are using brackets [
and ]
, the result classes are different. Therefore the operations that can be done on them are also different.
>> whos
Name Size Bytes Class Attributes
A 2x5 80 double
s 1x13 26 char
In fact, the array s
is not an array of the strings 'MATLAB '
,'is '
, and 'fun'
, it is just one string - an array of 13 characters. You would get the same results if it were defined by any of the following:
>> s = ['MAT','LAB ','is f','u','n'];
>> s = ['M','A','T','L','A','B,' ','i','s',' ','f','u','n'];
A regular MATLAB vector does not let you store a mix of variables of different classes, or a few different strings. This is where the cell
array comes in handy. This is an array of cells that each can contain some MATLAB object, whose class can be different in every cell if needed. Use curly braces {
and }
around the elements to store in a cell array.
>> C = {A; s}
C =
[2x5 double]
'MATLAB is fun'
>> whos C
Name Size Bytes Class Attributes
C 2x1 330 cell
Standard MATLAB objects of any classes can be stored together in a cell array. Note that cell arrays require more memory to store their contents.
Accessing the contents of a cell is done using curly braces {
and }
.
>> C{1}
ans =
1.0e+04 *
0.0001 -0.0002 0.0003 0.0001 1.5625
0.0003 Inf Inf NaN -Inf
Note that C(1)
is different from C{1}
. Whereas the latter returns the cell's content (and has class double
in out example), the former returns a cell array which is a sub-array of C
. Similarly, if D
were an 10 by 5 cell array, then D(4:8,1:3)
would return a sub-array of D
whose size is 5 by 3 and whose class is cell
. And the syntax C{1:2}
does not have a single returned object, but rater it returns 2 different objects (similar to a MATLAB function with multiple return values):
>> [x,y] = C{1:2}
x =
1 -2 3.14 0.8 15625
3.14159265358979 Inf Inf NaN -Inf
y =
MATLAB is fun