Lesson 10: Other Kinds of Arrays
Objectives
 Learn the different kinds of data used in MATLAB.
Background
Data Type
MATLAB provides 15 fundamental data type. Every data type stores data that is in the form of a matrix or array. You can watch Introducing MATLAB Fundamental Classes (Data Types).
10.1 Numeric Data Types
Numeric classes in MATLAB include signed and unsigned integers, and singleprecision and doubleprecision floatingpoint numbers. By default, MATLAB stores all numeric values as doubleprecision floating point. (You cannot change the default type and precision.) You can choose to store any number, or array of numbers, as integers or as singleprecision. Integer and single precision arrays offer more memoryefficient storage than double precision.
All numeric types support basic array operations, such as indexing, reshaping, and mathematical operations.
 Create Numeric Variables
 Convert Between Numeric Types
 Data Type Conversion
 Determination of Data Types
 Numeric Value Limits
 Create Numeric Variables
 Convert Between Numeric Types
 Data Type Conversion
 Determination of Data Types
 Numeric Value Limits
Create Numeric Variables
Syntax  Function  Description 

y = double(x)  Doubleprecision arrays (64bit)  Converts the values in x to double precision. 
y = single(x)  Singleprecision arrays (32bit)  Converts the values in x to single precision. 
y = int8(x)  8bit signed integer arrays  Converts the values in x to type int8. Values outside the range [2^{7}, 2^{7}1] map to the nearest endpoint. 
y = int16(x)  16bit signed integer arrays  Converts the values in x to type int16. Values outside the range [2^{15}, 2^{15}1] map to the nearest endpoint. 
y = int32(x)  32bit signed integer arrays  Converts the values in x to type int32. Values outside the range [2^{31}, 2^{31}1] map to the nearest endpoint. 
y = int64(x)  64bit signed integer arrays  Converts the values in x to type int64. Values outside the range [2^{63}, 2^{63}1] map to the nearest endpoint. 
y = uint8(x)  8bit unsigned integer arrays  Converts the values in x to type uint8. Values outside the range [0, 2^{8}1] map to the nearest endpoint. 
y = uint16(x)  16bit unsigned integer arrays  Converts the values in x to type uint16. Values outside the range [0, 2^{16}1] map to the nearest endpoint. 
y = uint32(x)  32bit unsigned integer arrays  Converts the values in x to type uint32. Values outside the range [0, 2^{32}1] map to the nearest endpoint. 
y = uint64(x)  64bit unsigned integer arrays  Converts the values in x to type uint64. Values outside the range [0, 2^{64}1] map to the nearest endpoint. 
Create Different Data Types
Create a script file with the following code:
str = 'Hello World!'
n = 2345
d = double(n)
un = uint32(789.50)
rn = 5678.92347
c = int32(rn)
When the above code is executed, it produces the following result in the Command Window:
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5.6789e+03
c = 5679
Create 8bit signed integer array
Variables in MATLAB of data type (class) int8 are stored as 1×8 (8bit) signed integers, and an uint8 array from 1 to 10.
>> y = int8(10);
>> whos y
Name Size Bytes Class Attributes
y 1x1 1 int8
>> x = uint8(1:10)
x = 1×10 uint8 row vector
1 2 3 4 5 6 7 8 9 10
Create an 16bit integer value from a floating number
>> a = pi
a = 3.1416
>> y = int8(a)
y = int8
3
Complex Numbers
The default data type for complex number is double. A double array needs 8 bytes to store it. A complex number requires 16bytes storage room, because both the real and imaginary components must be stored. If convert complex numbers to int8, it needs 2 byte (16bit) memory size.
>> F = 8  2i
F = 8.0000  2.0000i
>> class(F)
ans = 'double'
>> x = whos('F');
>> x.size
ans = 16
>> G = int8(F)
G = 8  2i
>> class(G)
ans = 'int8'
>> y = whos('G');
>> y.size
y = 2
Harmonic Series
Singleprecision floatingpoint numbers use only half the storage space of a doubleprecision number and thus store only half the information. Each value requires only 4 bytes, or 4 × 8 = 32 bits, of storage space. Since singleprecision numbers are allocated only half as much storage space, they cannot cover as large a range of values as doubleprecision numbers. It will make roundoff error when you calculate very small values.
Consider the following series: $\sum {\left( {\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{n} + \cdots } \right)} $
A series is the sum of a sequence of numbers, and this particular series is called the harmonic series , represented with the following shorthand notation:
$\sum\limits_{n = 1}^\infty {\frac{1}{n}} $
The harmonic series diverges; that is, it just keeps getting bigger as you add more terms together. You can represent the first 10 terms of the harmonic sequence with the following commands:
% Change the format to rational
format rat
n = 1:10;
harmonic = 1./n
harmonic = 1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10
Or you can use the short format, which shows decimal representations of the numbers:
format short
harmonic
harmonic = 1.0000 0.5000 0.3333 0.2500 0.2000
0.1667 0.1429 0.1250 0.1111 0.1000
By default, the data are stored as doubledouble precision floatingpoint numbers inside the computer. By calculating the partial sums (also called cumulative sums), we can see how the value of the sum of these numbers changes as we add more terms:
partialSum = cumsum(harmonic)
partialSum =
1.0000 1.5000 1.8333 2.0833 2.2833
2.4500 2.5929 2.7179 2.8290 2.9290
The cumulative sum (cumsum) function calculates the sum of the values in the array up to the element number displayed.
The only problem with this process is that the values in harmonic keep getting smaller and smaller. Eventually, when n is big enough, 1./n is so small that the computer can't distinguish it from zero. This happens when the number system does not have enough space to store the value.
Convert Between Numeric Types
Convert variable to different data type.
Syntax  Description 

B = cast(A,newclass)  Converts A to the data type (class) newclass, where newclass is the name of a builtin data type compatible with A. The cast function truncates any values in A that are outside the range of newclass to the nearest endpoint. When converting a floatingpoint number to an integer, the cast function rounds the number to the nearest integer. If the floatingpoint number has a fractional part of exactly 0.5, then it rounds away from zero to the integer with larger magnitude. 
B = cast(A,'like',p)  Converts A to the same data type, sparsity, and complexity (real or complex) as the variable p. If A and p are both real, then B is also real. Otherwise, B is complex. 
Convert data type without changing underlying
Syntax  Description 

Y = typecast(X,type)  Converts the bit patterns of X to the data type specified by type without changing the underlying data. X must be a full, noncomplex, numeric scalar or vector. 
Example 2
Set X to a 1×3 vector of 32bit integers, then cast it to an 8bit integer type:
>> X = uint32([1 255 256])
X = 1 255 256
Running this on a littleendian system produces the following results. Each 32bit value is divided up into four 8bit segments
>> Y = typecast(X, 'uint8')
Y = 1 0 0 0 255 0 0 0 0 1 0 0
The third element of X, 256, exceeds the 8 bits that it is being converted to in Y(9) and thus overflows to Y(10):
>> Y(9:12)
ans = 0 1 0 0
Note that length(Y) is equal to 4.*length(X). Also note the difference between the output of typecast versus that of cast:
>> Z = cast(X, 'uint8')
Z = 1 255 255
Example 3
This example casts a smaller data type (uint8) into a larger one (uint16). Displaying the numbers in hexadecimal format makes it easier to see just how the data is being rearranged:
>> format hex
>> X = uint8([44 55 66 77])
X = 2c 37 42 4d
The first typecast is done on a bigendian system. The four 8bit segments of the input data are combined to produce two 16bit segments
>> Y = typecast(X, 'uint16')
Y = 2c37 424d
The second is done on a littleendian system. Note the difference in byte ordering:
>> Y = typecast(X, 'uint16')
Y = 372c 4d42
You can format the littleendian output into bigendian (and vice versa) using the swapbytes function:
>> Y = swapbytes(typecast(X, 'uint16'))
Y = 2c37 424d
Example 4
This example attempts to make a 32bit value from a vector of three 8bit values. MATLAB issues an error because there are an insufficient number of bytes in the input:
>> format hex
>> typecast(uint8([120 86 52]), 'uint32')
Error using typecast
Too few input values to make output type.
Repeat the example, but with a vector of four 8bit values, and it returns the expected answer:
>> typecast(uint8([120 86 52 18]), 'uint32')
ans = 12345678
Data Type Conversion
Data Type Conversion
MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions −
Syntax  Function  Description 

C = char(A)  Convert to character array (string)  Converts array A into a character array. 
C = char(A1,...,An)  Converts the arrays A1,...,An into a single character array. After conversion to characters, the input arrays become rows in C. The char function pads rows with blank spaces as needed. If any input array is an empty character array, then the corresponding row in C is a row of blank spaces. The input arrays A1,...,An cannot be string arrays, cell arrays, or categorical arrays. A1,...,An can be of different sizes and shapes. 

C = char(D)  Converts a datetime, duration, or calendar duration array into a character array in the format specified by the Format property of D. The output contains one date or duration in each row.  
C = char(D,fmt)  Represents dates or durations in the specified format, such as 'HH:mm:ss'.  
C = char(D,fmt,locale)  Represents dates or durations in the specified locale, such as 'en_US'. The locale affects the language used to represent character vectors such as month and day names.  
chr = int2str(N)  Convert integer data to string  Treats N as a matrix of integers and converts it to a character array that represents the integers. If N contains floatingpoint values, int2str rounds them before conversion. 
chr = mat2str(X)  Convert matrix to string  Converts the numeric matrix X into a character vector that represents the matrix, with up to 15 digits of precision. You can use chr as input to the eval function. For example, A = eval(chr) reproduces the values from the original matrix to the precision specified in chr. 
chr = mat2str(X,n)  Converts X using n digits of precision.  
chr = mat2str(___,'class')  Includes the name of the class, or data type, of X in chr. You can use this syntax with any of the arguments from the previous syntaxes. If you use this syntax to produce chr, then A = eval(chr) also reproduces the data type of the original matrix 

s = num2str(A)  Convert number to string  Converts a numeric array into a character array that represents the numbers. The output format depends on the magnitudes of the original values. num2str is useful for labeling and titling plots with numeric values. 
s = num2str(A,precision)  Returns a character array that represents the numbers with the maximum number of significant digits specified by precision.  
s = num2str(A,formatSpec))  Applies a format specified by formatSpec to all elements of A.  
X = str2double(str)  Convert string to doubleprecision value  Converts the text in str to double precision values. str contains text that represents real or complex numeric values. str can be a character vector, a cell array of character vectors, or a string array. If str is a character vector or string scalar, then X is a numeric scalar. If str is a cell array of character vectors or a string array, then X is a numeric array that is the same size as str. 
X = str2num(chr)  Convert string to number  Converts a character array or string scalar to a numeric matrix. The input can include spaces, commas, and semicolons to indicate separate elements. If str2num cannot parse the input as numeric values, then it returns an empty matrix. The str2num function does not convert cell arrays or nonscalar string arrays, and is sensitive to spacing around + and  operators. In addition, str2num uses the eval function, which can cause unintended side effects when the input includes a function name. To avoid these issues, use str2double. 
[X,tf] = str2num(chr)  Additionally returns a second output argument that is 1 (true) if str2num successfully converts chr. Otherwise, str2num returns 0 (false).  
unicodestr = native2unicode(bytes)  Convert numeric bytes to Unicode characters  Converts a numeric vector, bytes, from the user default encoding to a Unicode character representation. native2unicode treats bytes as a vector of 8bit bytes, and each value must be in the range [0,255]. The output argument unicodestr is a character vector having the same general array shape as bytes. 
unicodestr = native2unicode(bytes, encoding)  Converts bytes to a Unicode representation with the assumption that bytes is in the character encoding scheme specified by encoding. The input argument encoding must have no characters ('') or it must be a name or alias for an encoding scheme. Some examples are 'UTF8', 'latin1', 'USASCII', and 'Shift_JIS'. If encoding is unspecified or has no characters (''), the default encoding scheme is used. encoding can be a character vector or a string scalar.  
bytes = unicode2native(unicodestr)  Convert Unicode characters to numeric bytes  Converts the input Unicode character representation, unicodestr, to the user default encoding, and returns the bytes as a uint8 vector, bytes. Output vector bytes has the same general array shape as the unicodestr input. You can save the output of unicode2native to a file using the fwrite function. unicodestr can be a character vector or a string scalar. 
bytes = unicode2native(unicodestr,encoding)  Converts unicodestr to the character encoding scheme specified by encoding. The input argument encoding must have no characters ('') or must be a name or alias for an encoding scheme. Some examples are 'UTF8', 'latin1', 'USASCII', and 'Shift_JIS'. If encoding is unspecified or has no characters (''), the default encoding scheme is used. encoding can be a character vector or a string scalar.  
d = base2dec('strn', base)  Convert base N number string to decimal number  Converts strn, text representing a number in the base specified by base, into its decimal (base 10) equivalent. base must be an integer between 2 and 36. strn must represent a nonnegative integer value. If strn represents an integer value greater than the value returned by flintmax, then base2dec might not return an exact conversion. 
d = bin2dec('binarystr')  Convert binary number string to decimal number  Interprets binarystr, text that represents a binary number, and returns the equivalent decimal number. binarystr must represent a nonnegative integer value smaller than or equal to the value returned by flintmax. binarystr can be a character array, a cell array of character vectors, or a string array. bin2dec ignores any space characters in the input text. 
str = dec2base(d, base)  Convert decimal to base N number in string  Converts the nonnegative integer d to the specified base. d must be a nonnegative integer smaller than the value returned by flintmax, and base must be an integer between 2 and 36. The returned argument str is a character vector. 
str = dec2base(d, base, n)  Produces a representation with at least n digits.  
str = dec2bin(d)  Convert decimal to binary number in string  Returns the binary representation of d as a character vector. d must be a nonnegative integer. If d is greater than the value returned by flintmax, then dec2bin might not return an exact representation of d. 
str = dec2bin(d,n)  Produces a binary representation with at least n bits. The output of dec2bin is independent of the endian settings of the computer you are using. 

str = dec2hex(d)  Convert decimal to hexadecimal number in string  Returns the hexadecimal representation of d as a character vector. d must be a nonnegative integer. If d is an integer greater than the value returned by flintmax, then dec2hex might not return an exact representation. MATLAB converts noninteger inputs, such as those of class double or char, to their integer equivalents before converting to hexadecimal. 
str = dec2hex(d, n)  Produces a hexadecimal representation with at least n digits.  
d = hex2dec('hex_value')  Convert hexadecimal number string to decimal number  Converts hex_value to its floatingpoint integer representation. The argument hex_value is a hexadecimal integer stored as text. If the value of hex_value is greater than the hexadecimal equivalent of the value returned by flintmax, then hex2dec might not return an exact conversion. The input argument hex_value can be a character array, cell array of character vectors, or string array. 
n = hex2num(S)  Convert hexadecimal number string to doubleprecision number  Where S contains 16 characters representing a hexadecimal number, returns the IEEE doubleprecision floatingpoint number n that it represents. Fewer than 16 characters are padded on the right with zeros. S can be a character array, a cell array of character vectors, or a string array. 
h = num2hex(X)  Convert singles and doubles to IEEE hexadecimal strings  If X is a single or double precision array with n elements, then num2hex(X) is an n×8 or n×16 character array in which each row contains the hexadecimal floatingpoint representation of a number. The same representation is printed with format hex. 
A = cell2mat(C)  Convert cell array to numeric array  Converts a cell array into an ordinary array. The elements of the cell array must all contain the same data type, and the resulting array is of that data type. 
structArray = cell2struct(cellArray, fields, dim)  Convert cell array to structure array  Creates a structure array, structArray, from the information contained within cell array cellArray. The fields argument specifies field names for the structure array. This argument is a character array, a cell array of character vectors, or a string array. The dim argument tells MATLAB which axis of the cell array to use in creating the structure array. Use a numeric double to specify dim. To create a structure array with fields derived from N rows of a cell array, specify N field names in the fields argument, and the number 1 in the dim argument. To create a structure array with fields derived from M columns of a cell array, specify M field names in the fields argument and the number 2 in the dim argument. The structArray output is a structure array with N fields, where N is equal to the number of fields in the fields input argument. The number of fields in the resulting structure must equal the number of cells along dimension dim that you want to convert. 
C = cellstr(A)  Create cell array of strings from character array  Converts A to a cell array of character vectors. The input array A can be a character array, a categorical array, or, starting in R2016b, a string array. 
C = cellstr(D)  Converts a datetime, duration, or calendar duration array into a cell array of character vectors in the format specified by the Format property of D. The output has the same dimensions as D.  
C = cellstr(D,fmt)  Represents dates or durations in the specified format. For example, cellstr(D,'HH:mm:ss') represents the times associated with each element of D.  
C = cellstr(D,fmt,locale)  Represents dates or durations in the specified locale. For example, cellstr(D,'ddMMMyyyy','en_US') represents the dates associated with each element of D using the en_US locale. The locale affects the language used to represent character vectors such as month and day names.  
C = mat2cell(A,dim1Dist,...,dimNDist)  Convert array to cell array with potentially different sized cells  Divides array A into smaller arrays and returns them in cell array C. The vectors dim_{1}Dist,...dim_{N}Dist specify how to divide the rows, the columns, and (when applicable) the higher dimensions of A. The smaller arrays in C can have different sizes. A can have any data type. 
C = mat2cell(A,rowDist)  Divides array A into an n×1 cell array C, where n equals the number of elements in rowDist.  
C = num2cell(A)  Convert array to cell array with consistently sized cells  Converts array A into cell array C by placing each element of A into a separate cell in C. The num2cell function converts an array that has any data type — even a nonnumeric type. 
C = num2cell(A,dim)  Splits the contents of A into separate cells of C, where dim specifies which dimensions of A to include in each cell. dim can be a scalar or a vector of dimensions. For example, if A has 2 rows and 3 columns, then:


C = struct2cell(S)  Convert structure to cell array  Converts a structure into a cell array. The cell array C contains values copied from the fields of S. The struct2cell function does not return field names. To return the field names in a cell array, use the fieldnames function. 
Example
Create a script file with the following code:
% Convert a numeric array to a character array.
A = [67 83 85 76 65]; C1 = char(A)
% Convert Multiple Arrays to Character Array
A1 = [65 66; 67 68]; A2 = 'abcd';
C2 = char(A1, A2)
% Convert an integer to string
C3 = int2str(256)
C4 = int2str(3.14159)
% Convert a numeric matrix to a character vector
C5 = mat2str([3.85 2.91; 7.74 8.99])
% Convert Character Vectors to Numbers
str = string('81470.5'); C6 = str2double(str)
% Decimal 23 converts to binary 010111
C7 = dec2bin(23)
% To convert decimal 1023 to hexadecimal
C8 = dec2hex(1023)
% To convert hex value to its floatingpoint integer representation
C9 = hex2dec('3ff')
% Converts 2310 to base 2, returning the character vector '10111'
C10 = dec2base(23, 2)
When you execute the script file, it will produces the following result in the Command Window:
C1 = CSULA
C2 = 3×4 char array
'AB '
'CD '
'abcd'
C3 = '256'
C4 = '3'
C5 = '[3.85 2.91;7.74 8.99]'
C6 = 8.1471e+04
C7 = 10111
C8 = 3FF
C9 = 1023
C10 = '10111'
Determination of Data Types
Determination of Data Types
MATLAB provides various functions for identifying data type of a variable. Following table provides the functions for determining the data type of a variable −
Syntax  Function  Description 

is  Detect state  
tf = isa(A,dataType) 
Determine if input is object of specified class  Returns 1 (true) if A has the data type specified by dataType. Otherwise, it returns 0 (false). The input argument A can have any data type. If A is an object, then isa returns 1 if dataType is either the class of A or a superclass of A. 
tf = isa(A,typeCategory)  Returns 1 (true) if the data type of A belongs to the category specified by typeCategory. Otherwise, it returns 0 (false). If A is an object, then isa returns 1 if the class of A, or any superclass of A, belongs to the specified category. 

tf = iscell(A)  Determine whether input is cell array  Returns logical 1 (true) if A is a cell array and logical 0 (false) otherwise. 
tf = iscellstr(A)  Determine whether input is cell array of strings  Returns logical 1 (true) if A is a cell array of character vectors (or an empty cell array), and logical 0 (false) otherwise. A cell array of character vectors is a cell array where every cell contains a character vector. 
tf = ischar(A)  Determine whether item is character array  Returns logical 1 (true) if A is a character array and logical 0 (false) otherwise. 
tf = isfield(S, field)  Determine whether input is structure array field  Returns 1 if field is the name of a field of the structure array S. Otherwise, it returns 0. If field is an array that contains multiple names, then tf is a logical array that has the same size. 
tf = isfinite(A)  Determine which array elements are finite  Returns a logical array containing 1 (true) where the elements of the array A are finite, and 0 (false) where they are infinite or NaN. If A contains complex numbers, isfinite(A) contains 1 for elements with finite real and imaginary parts, and 0 for elements where either part is infinite or NaN. 
tf = isfloat(A)  Determine if input is floatingpoint array  Returns true if A is a floatingpoint array and false otherwise. The floatingpoint types are single and double, and subclasses of single and double. 
tf = ishandle(h)  Test for valid graphics or Java object handle  Returns an array whose elements are 1 where the elements of h are graphics or Java object handles, and 0 where they are not. 
tf = ishghandle(h)  True for Handle Graphics object handles  Returns an array that contains 1's where the elements of h are handles to existing graphics objects and 0's where they are not. Differs from ishandle in that Simulink objects handles return false. 
ti = isinf(A)  Determine which array elements are infinite  Returns a logical array containing 1 (true) where the elements of the array A are Inf or Inf, and 0 (false) where they are not. If A contains complex numbers, isinf(A) contains 1 for elements with infinite real or imaginary part, and 0 for elements where both real and imaginary parts are finite or NaN. 
ti = isinteger(A)  Determine whether input is integer array  Returns logical 1 (true) if A is an array of integer type. Otherwise, it returns logical 0 (false). 
tf = isjava(A)  Determine if input is Java object  Returns logical 1 (true) if object A is a Java object. Otherwise, it returns logical 0 (false). 
tf = islogical(A)  Determine if input is logical array  Returns true if A is a logical array and false otherwise. islogical also returns true if A is an instance of a class that is derived from the logical class. 
tn = isnan(A)  Determine which array elements are NaN  Returns a logical array containing 1 (true) where the elements of A are NaN, and 0 (false) where they are not. If A contains complex numbers, isnan(A) contains 1 for elements with either real or imaginary part is NaN, and 0 for elements where both real and imaginary parts are not NaN. 
tn = isnumeric(A)  Determine whether input is numeric array  Returns logical 1 (true) if A is an array of numeric data type. Otherwise, it returns logical 0 (false). Numeric types in MATLAB include: int8, int16, int32, int64, uint8, uint16, uint32, uint64, single, and double. 
tf = isobject(A)  Determine if input is MATLAB object  Returns true if A is an object of a MATLAB class. Otherwise, it returns false. Instances of MATLAB numeric, logical, char, cell, struct, and function handle classes return false. Use isa to test for any of these types. 
tr = isreal(A)  Determine whether array is real  Returns logical 1 (true) when a numeric array A does not have an imaginary part, and logical 0 (false) otherwise. 
tf = isscalar(A)  Determine whether input is scalar  Returns logical 1 (true) if A is a scalar. Otherwise, it returns logical 0 (false). A scalar is a twodimensional array that has a size of 1×1. 
tf = isstruct(A)  Determine whether input is structure array  Returns logical 1 (true) if A is a MATLAB structure and logical 0 (false) otherwise. 
tf = isvector(A)  Determine whether input is vector  Returns logical 1 (true) if A is a vector. Otherwise, it returns logical 0 (false). A vector is a twodimensional array that has a size of 1×N or N×1, where N is a nonnegative integer. 
className = class(obj)  Determine class of object  Returns the name of the class of obj. 
validateattributes(A,classes,attributes)  Check validity of array  Validates that array A belongs to at least one of the specified classes (or its subclass) and has all the specified attributes. If A does not meet the criteria, then MATLAB throws an error and displays a formatted error message. Otherwise, validateattributes completes without displaying any output. 
validateattributes(A,classes,attributes, argIndex) 
Includes the position of the input in your function argument list as part of any generated error messages.  
validateattributes(A,classes,attributes funcName) 
Includes the specified function name in generated error identifiers.  
validateattributes(A,classes,attributes funcName,varName) 
Includes the specified variable name in generated error messages.  
validateattributes(A,classes,attributes, funcName,varName,argIndex) 
Includes the specified information in generated error messages or identifiers.  
whos  List variables in workspace, with sizes and types  Lists in alphabetical order the names, sizes, and types of all variables in the currently active workspace. 
whos file filename  Lists variables in the specified MATfile.  
whos global  Lists variables in the global workspace.  
whos ___ variables  Lists only the specified variables. You can specify variables with any of the arguments in the previous syntaxes.  
S = whos(__)  Stores information about the variables in the structure array S. 
Example
Create a script file with the following code:
x = 3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
When you execute the script file, it will produces the following result in the Command Window:
x = 3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
Numeric Value Limits
Floatingpoint relative accuracy
Syntax  Description 

d = eps  Returns the distance from 1.0 to the next larger doubleprecision number, that is, 2^{52}. 
d = eps(x)  Where x has data type single or double, returns the positive distance from abs(x) to the next larger floatingpoint number of the same precision as x. If x has type duration, then eps(x) returns the next larger duration value. The command eps(1.0) is equivalent to eps. 
d = eps(datatype)  Returns eps according to the data type specified by datatype, which can be either 'double' or 'single'. The syntax eps('double') (default) is equivalent to eps, and eps('single') is equivalent to eps(single(1.0)). 
Largest consecutive integer in floatingpoint format
Syntax  Description 

f = flintmax  Returns the largest consecutive integer in IEEE double precision, which is 2^{53}. Above this value, doubleprecision format does not have integer precision, and not all integers can be represented exactly. 
f = flintmax(precision)  Returns the largest consecutive integer in IEEE single or double precision. flintmax returns single (2^{24}) for single precision and 2^{53} for double precision. 
Create array of all Inf values
Syntax  Description 

X = Inf  Returns the scalar representation of positive infinity. Operations return Inf when their result is too large to represent as a floating point number, such as 1/0 or log(0). For doubleprecision, Inf represents numbers larger than realmax. For singleprecision, Inf represents numbers larger than realmax('single'). 
X = Inf(n)  Returns an n×n matrix of Inf values. 
X = Inf(sz1,...,szN)  Returns an sz_{1}×...×sz_{N} array of Inf values, where sz_{1},...,sz_{N} indicate the size of each dimension. For example, Inf(3,4) returns a 3×4 matrix. 
X = Inf(sz)  Returns an array of Inf values, where the size vector sz defines size(X). For example, Inf([3 4]) returns a 3×4 matrix. 
X = Inf(___,typename)  Returns an array of Inf values of data type typename, which can be either 'single' or 'double'. 
X = Inf(___,'like',p)  Returns an array of Inf values of the same data type, sparsity, and complexity (real or complex) as p. You can specify typename or 'like' but not both. 
Largest value of specific integer type
Syntax  Description 

v = intmax  Returns the largest value of the 32bit signed integer type. 
v = intmax(type)  Returns the largest value of the specified integer type. When you convert a value that is larger than intmax(type) into the integer type type, the value becomes intmax(type). 
Smallest value of specified integer type
Syntax  Description 

v = intmin  It is the smallest value that can be represented in the MATLAB software with a 32bit integer. Any value smaller than the value returned by intmin saturates to the intmin value when cast to a 32bit integer. 
v = intmin('classname')  It is the smallest positive value in the integer class classname. Valid values for the string classname are 'int8', 'int16', 'int32', 'uint8', 'uint16', 'uint32'. 
Create array of all NaN values
Syntax  Description 

X = NaN  Returns the scalar representation of "not a number". Operations return NaN when they have undefined numeric results, such as 0/0 or 0*Inf. 
X = NaN(n)  Returns an n×n matrix of NaN values. 
X = NaN(sz1,...,szN)  Returns an sz_{1}×...×sz_{N} array of NaN values, where sz_{1},...,sz_{N} indicate the size of each dimension. For example, NaN(3,4) returns a 3×4 matrix. 
X = NaN(sz)  Returns an array of NaN values, where the size vector sz defines size(X). For example, NaN([3 4]) returns a 3×4 matrix. 
X = NaN(___,typename)  Returns an array of NaN values of data type typename, which can be either 'single' or 'double'. 
X = NaN(___,'like',p)  Returns an array of NaN values of the same data type, sparsity, and complexity (real or complex) as p. You can specify typename or 'like' but not both. 
Largest positive floatingpoint number
Syntax  Description 

f = realmax  Returns the largest finite floatingpoint number in IEEE double precision. This is equal to (22^{52})*2^{1023}. 
f = realmax(precision)  Returns the largest finite floatingpoint number in IEEE single or double precision. This is equal to realmax for double precision, and to single ((22^{23})*2^{127}) for single precision. 
Smallest normalized floatingpoint number
Syntax  Description 

f = realmin  Returns the smallest positive normalized floatingpoint number in IEEE double precision. This is equal to 2^{1022}. 
f = realmin(precision)  Returns the smallest positive normalized floatingpoint number in IEEE single or double precision. This is equal to realmin for double precision, and to single (2^{126}) for single precision. 
Practice Exercise 10.1
 Enter the following list of numbers into arrays of each of the numeric data types: $[1, 4 ,6; 3, 15, 24,; 2, 3, 4]$
 Doubleprecision floating point — name this array A
 Singleprecision floating point — name this array B
 16bit singedinteger — name this array C
 32bit unsigned integer — name this array D
 Continue the question 1. Create a new matrix E by adding A to B:
$E = A + B$
What data type is the result?  Define x as an integer data type equal to 1, and y as an integer data type equal to 3.
 What is the result of the calculation x/y ?
 What is the data type of the result?
 What happens when you perform the division when x is defined as the integer 2 and y as integer 3?
10.2 Character and String Data
Creating and Using Character and String Arrays
Creating and Using Character and String Arrays
Starting in R2016b, you can represent text using string arrays instead of character arrays. Each element of a string array stores a sequence of characters. The sequences can have different lengths without padding, such as "yes" and "no". A string array that has only one element is also called a string scalar.
You can index into, reshape, and concatenate string arrays using standard array operations, and you can append text to strings using the + operator. If a string array represents numbers, then you can convert it to a numeric array using the double function.
Syntax  Description 

str = string(A)  Converts the input array to a string array. 
str = string(D)  Converts a datetime, duration, or calendar duration array into a string array in the format specified by the Format property of D. The output contains one date or duration in each row. 
str = string(D,fmt)  Represents dates or durations in the specified format, such as 'HH:mm:ss'. 
str = string(D,fmt,locale)  Represents dates or durations in the specified locale, such as 'en_US'. The locale affects the language used to represent strings such as month and day names. 
Character Array
A twodimensional character arrays can be created only if the number of elements in each row is the same. Thus, a list of names such as the following won't work, because each name has a different number of characters:
>> A = ['Vicky';'Ryan';'Kevin';'David';'Michael']
??? Error using ==> vertcat
All rows in the bracketed expression must have the same number of columns.
The char function "pads" a character array with spaces, so that every row has the same number of elements:
>> A = char('Vicky','Ryan','Kevin','David','Michael')
A = 5×7 char array
'Vicky '
'Ryan '
'Kevin '
'David '
'Michael'
A is 5×7 character array. Notice that commas are used between each string in the char function.
String Array
You can use string function to create a string array.
>> B = string({'Vicky';'Ryan';'Kevin';'David';'Michael'})
B = 5×1 string array
"Vicky"
"Ryan"
"Kevin"
"David"
"Michael"
The resulting string is a 5×1 string array. Each name is stored as a string element in the array. Notice the double quotes used to indicate a string, versus the single quotes used to indicate a character array.
You can create a string by enclosing a piece of text in double quotes.
>> str = "Hello, world"
str = "Hello, world"
Another way to create a string array is to concatenate strings into an array using square brackets ([]), just as you can concatenate numbers into a numeric array.
>> str = ["Mercury","Gemini","Apollo";
"Skylab","Skylab B","ISS"]
str = 2x3 string array
"Mercury" "Gemini" "Apollo"
"Skylab" "Skylab B" "ISS"
Combine Character and Double Array
The array score contains test scores for the students in the character array student. If we try to combine these two arrays, we will get a strange result, because they are two different data types. The MATLAB will convert the score array to characters.
>> score = [84; 100; 88; 95; 100];
>> student_c = char('Vicky','Ryan','Kevin','David','Michael');
>> results = [student_c, score]
results = 5×8 char array
'Vicky T'
'Ryan d'
'Kevin X'
'David _'
'Michaeld'
When doubles and characters are used in the same array, MATLAB converts all the information to characters.
The num2str function is used to convert the double score matrix to a matrix composed of character data.
>> score_c = num2str(score)
score_c = 5×3 char array
' 84'
'100'
' 88'
' 95'
'100'
Now, we can combine student_c, the character array of names, with score_c, the character array of scores. The disp function also can be used to display the results:
>> results = [student_c, score_c]
results = 5×10 char array
'Vicky 84'
'Ryan 100'
'Kevin 88'
'David 95'
'Michael100'
>> disp([student_c, score_c])
Vicky 84
Ryan 100
Kevin 88
David 95
Michael100
Or, you can use the fprintf function in combination with a for loop to display the results:
for i=1:length(score)
fprintf(' %10s %8.0f \n', student_c(i,:), score(i))
end
returns
Vicky 84
Ryan 100
Kevin 88
David 95
Michael 100
Combine String and Double Array
When we create a string array of the combined student and score data type by simple concatenating the two arrays:
>> score = [84; 100; 88; 95; 100];
>> student_s = string({'Vicky';'Ryan';'Kevin';'David';'Michael'});
>> R = [student_s, score]
R = 5×2 string array
"Vicky" "84"
"Ryan" "100"
"Kevin" "88"
"David" "95"
"Michael" "100"
The result is a 5×2 string array. Notice that the numbers have been converted to strings automatically. We can use fprintf to display the result:
>> fprintf(' %10s %10s \n', R')
Vicky 84
Ryan 100
Kevin 88
David 95
Michael 100
Split String and Find Unique Words
To find the unique words in a string, split it on space characters and call the unique function.
First, create a string scalar.
>> str = "A horse! A horse! My kingdom for a horse!";
Remove the exclamation point.
>> str = erase(str,"!")
str = "A horse A horse My kingdom for a horse"
Convert all letters in str to lowercase characters.
>> str = lower(str)
str = "a horse a horse my kingdom for a horse"
Split str on space characters using the split function. split discards the space characters and returns the result as a string array.
>> str = split(str)
str = 9x1 string array
"a"
"horse"
"a"
"horse"
"my"
"kingdom"
"for"
"a"
"horse"
Find the unique words in str using the unique function.
>> str = unique(str)
str = 5x1 string array
"a"
"for"
"horse"
"kingdom"
"my"
Convert Character Vector
>> A = 'Four score and seven years ago'
A = 'Four score and seven years ago'
>> str = string(A)
str = "Four score and seven years ago"
str contains the same characters as A. But while A is a character vector, str is a string scalar.
>> c = size(A)
c = 1×2
1 30
>> s = size(str)
s = 1×2
1 1
To return the number of characters in str, use the strlength function.
>> n = strlength(str)
n = 30
Convert Cell Array
Convert a cell array of character vectors to a string array.
>> A = {'Mercury','Gemini','Apollo';...
'Skylab','Skylab B','ISS'}
A = 2x3 cell array
{'Mercury'} {'Gemini' } {'Apollo'}
{'Skylab' } {'Skylab B'} {'ISS' }
>> str = sting(A)
str = 2x3 string array
"Mercury" "Gemini" "Apollo"
"Skylab" "Skylab B" "ISS"
To access the second element in the first row of str, index using smooth parentheses. You can access strings in a string array with matrix indexing, just as you would access elements of a numeric array.
>> str(1,2)
ans = "Gemini"
Access the third column.
>> str(:, 3)
ans = 2x1 string array
"Apollo"
"ISS"
Convert Strings That Represent Numbers
Create a string array in which each element represents a number. To convert the string array to a numeric array, use the double function.
>> str = ["256","3.1416","8.9e3"]
>> X = double(str)
X = 1×3
256.0000 3.1416 0.0089
When the input argument is a string array, the double function treats each element as the representation of a floatingpoint value. However, when the input is a character array, double instead converts each character to a number representing its Unicode value.
As an alternative, use the str2double function. str2double is suitable when the input argument might be a string array, character vector, or cell array of character vectors.
>> Y = str2double(str)
Y = 1×3
256.0000 3.1416 0.0089
>> C = '2.7183';
>> Z = str2double(C)
Z = 2.7183
Convert Duration Array
Create a duration array, D. Then convert D to a string array.
>> D = hours(23:25) + minutes(8) + seconds(1.2345);
>> str = string(D)
str = 1x3 string array
"23.134 hr" "24.134 hr" "25.134 hr"
str is a string array with one duration value per element. str is the same size as D.
Specify the format of the duration values in str.
>> str = string(D,'hh:mm')
str = 1x3 string array
"23:08" "24:08" "25:08"
Character Encoding Strategies
Character Encoding Strategies
All information in computers is stored as a series of zeros and ones, also known as binary numbers. Therefore, all characters need to be converted to binary numbers. There are two major coding schemes to do this: ASCII and EBCDIC. Most small computers use the ASCII codeing scheme, whereas many mainframes and supercomputers use EBCDIC.
When a character is changed to integer or double, the resulting number is the decimal equivalent in the ASCII coding system.
>> double('a')
ans = 97
>> uint8('x')
ans = 120
Conversely, when we use the char function on a double, we get the character represented by that decimal number in ASCII.
>> char(98)
ans = 'b'
When a matrix is created that contains both numeric and character information, MATLAB will converts all data to character information:
>> k = ['a', 98]
k = 'ab'
>> L = ['a', 3]
L = 'a '
The character b is equivalent to the number 98.
Note: Not all numbers have a character equivalent. If this is the case, they are represented as a blank or a box in the resulting character array.
10.3 Logical Data
Most computer languages, include MATLAB, use value zero and one to denote false and true. Therefore, the logical arrays look like arrays of ones and zeros:
>> T = [true, false, true]
T = 1 0 1
Usually, we are not using this way to create logical arrays. Instead, use logical operations to get the logical results in the array.
>> x = 1:5;
>> y = [2, 0, 1, 9, 4];
>> z = x > y
returns
z = 0 1 1 0 1
We can interpret this to mean that x > y is false for elements 1 and 4, and true for elements 2, 3, and 5. We can use the find function to find out which elements in the x array are greater than the corresponding elements of the y array:
>> find(x > y)
ans = 2 3 5
10.4 Other Types of Arrays
Sparse Arrays
Sparse Arrays
Sparse matrices provide efficient storage of doubleprecision or logical arrays that has a large percentage of zeros. While full (or dense) matrices store every single element in memory regardless of value, sparse matrices store only the nonzero elements and their row indices. For this reason, using sparse matrices can significantly reduce the amount of memory required for data storage.
Syntax  Description 

S = sparse(A)  Converts a full matrix into sparse form by squeezing out any zero elements. If a matrix contains many zeros, converting the matrix to sparse storage saves memory. 
S = sparse(m,n)  Generates an m×n all zero sparse matrix. 
S = sparse(i,j,v)  Generates a sparse matrix S from the triplets i, j, and v such that S(i(k),j(k)) = v(k). The max(i)bymax(j) output matrix has space allotted for length(v) nonzero elements. sparse adds together elements in v that have duplicate subscripts in i and j. If the inputs i, j, and v are vectors or matrices, they must have the same number of elements. Alternatively, the argument v and/or one of the arguments i or j can be scalars. 
S = sparse(i,j,v,m,n)  Specifies the size of S as m×n. 
S = sparse(i,j,v,m,n,nz)  Allocates space for nz nonzero elements. Use this syntax to allocate extra space for nonzero values to be filled in after construction. 
Save Memory Using Sparse Storage
Create a 10,000×10,000 full storage identity matrix.
>> A = eye(10000);
>> whos A
Name Size Bytes Class Attributes
A 10000x10000 800000000 double
Each element (double) needs 8bytes storage room, This matrix uses 800megabytes of memory.
Convert the matrix to sparse storage.
>> S = sparse(A);
>> whos S
Name Size Bytes Class Attributes
S 10000x10000 240008 double sparse
In sparse form, the same matrix uses roughly 0.25megabytes of memory. In this case, you can avoid full storage completely by using the speye function, which creates sparse identity matrices directly.
Categorical Arrays
Categorical Arrays
A categorical array stores information from a finite list of categories. It is often used as part of a table of related information. You can create a categorical array using curly braces({}) and the categorical function.
Syntax  Description 

C = categories(A)  Returns a cell array of character vectors containing the categories of the categorical array, A. 
List Categories in Categorical Array
Create a categorical array, A.
>> A = categorical({'plane' 'car' 'train' 'car' 'plane'})
A = 1×5 categorical array
plane car train car plane
A is a 1×5 categorical array.
Display the categories of A.
>> C = categories(A)
C = 3×1 cell array
{'car' }
{'plane'}
{'train'}
Since you created A by specifying only an input array, the categories appear in alphabetical order.
List Categories in Ordinal Categorical Array
Create an ordinal categorical array.
>> A = categorical({'medium' 'large'; 'small' 'xlarge'; 'large' 'medium'},...
{'small' 'medium' 'large' 'xlarge'},'Ordinal',true)
A = 3×2 categorical array
medium large
small xlarge
large medium
A is a 3×2 ordinal categorical array.
Display the categories of A.
>> C = categories(A)
C = 4×1 cell array
{'small' }
{'medium'}
{'large' }
{'xlarge'}
The categories appear in the order in which you specified them. Since A is ordinal, the categories have the mathematical ordering small < medium < large < xlarge.
Time Arrays
Time Arrays
Date and time data can be stored in a datatime array. These arrays have the advantage of allowing information to be stored using standard data and time nomenclature.
Syntax  Description 

t = datetime  Returns a scalar datetime array corresponding to the current date and time. 
t = datetime(relativeDay)  Uses the date specified by relativeDay. The relativeDay input can be 'today', 'tomorrow', 'yesterday', or 'now'. 
t = datetime(DateStrings)  Creates an array of datetime values from the text in DateStrings representing points in time. 
t = datetime(DateStrings,'InputFormat',infmt)  Interprets DateStrings using the format specified by infmt. All values in DateStrings must have the same format. To avoid ambiguities between similar formats, specify 'InputFormat' and its corresponding value, infmt. 
t = datetime(DateVectors)  Creates a column vector of datetime values from the date vectors in DateVectors. 
t = datetime(Y,M,D) t = datetime(Y,M,D,H,MI,S) t = datetime(Y,M,D,H,MI,S,MS) 
Creates an array of datetime values for corresponding elements of the Y, M, D, H, MI, S, and MS (year, month, day, hour, minute, second, and millisecond) arrays. The arrays must be of the same size (or any can be a scalar). You also can specify the input arguments as a date vector, [Y M D H MI S MS]. 
t = datetime(X,'ConvertFrom',dateType)  Converts the numeric values in X to a datetime array t. The dateType argument specifies the type of values in X. 
t = datetime(___,Name,Value)  Specifies additional options using one or more namevalue pair arguments, in addition to any of the input arguments in the previous syntaxes. For example, you can specify the display format of t using the 'Format' namevalue pair argument. 
Current Date and Time in Specific Time Zone
Specify the current date and time in the local system time zone.
>> t = datetime('now','TimeZone','local','Format','dMMMy HH:mm:ss Z')
t = datetime
22Oct2019 00:37:24 0700
Specify the current date and time in the time zone represented by Taipei, Taiwan.
>> t = datetime('now','TimeZone','Asia/Taipei','Format','dMMMy HH:mm:ss Z')
t = datetime
22Oct2019 15:37:24 +0800
Date and Time from Character Vectors
Create a datetime array from a cell array of character vectors.
>> DateStrings = {'20140526';'20140803'};
>> t = datetime(DateStrings,'InputFormat','yyyyMMdd')
t = 2×1 datetime array
26May2014
03Aug2014
The datetime values in t display using the default format, and not the format of the input dates.
Date and Time from String Array
You can create string arrays with the string function and convert them to datetime values. Convert the strings, specifying the input format as yyyyMMdd. The format must be specified as a character vector, even though str is a string array.
>> str = string({'20160324','20160419'});
>> t = datetime(str,'InputFormat','yyyyMMdd')
t = 1×2 datetime array
24Mar2016 19Apr2016
Time from Text Representing Fractional Seconds
Create a datetime value from text that represents a date and time to millisecond precision. To convert text in a format that the datetime function cannot parse without more information, specify the 'InputFormat' namevalue pair argument.
>> d = '20180625 11:23:37.712';
>> t = datetime(d,'InputFormat','yyyyMMdd HH:mm:ss.SSS')
t = datetime
25Jun2018 11:23:37
The conversion does keep the fractional seconds. However, by default datetime arrays do not display fractional seconds. To display them, specify either the 'Format' namevalue pair or the Format property.
>> t.Format = 'MMM dd, yyyy HH:mm:ss.SSS'
t = datetime
Jun 25, 2018 11:23:37.712
The 'InputFormat' argument applies only to conversions from input text. The Format property specifies the display for any datetime array.
Date and Time from Vectors
Create a datetime array from individual arrays of year, month, and day values.
Create sample numeric arrays of year values Y and day values D. In this case, the month value M is a scalar.
>> Y = [2014;2013;2012];
>> M = 01;
>> D = [31;30;31];
Create the datetime array.
>> t = datetime(Y,M,D)
t = 3×1 datetime array
31Jan2014
30Jan2013
31Jan2012
Specify a custom display format for the output, using the Format namevalue pair argument.
>> t = datetime(Y,M,D,'Format','eeee, MMMM d, y')
t = 3×1 datetime array
Friday, January 31, 2014
Wednesday, January 30, 2013
Tuesday, January 31, 2012
Multidimensional Arrays
Multidimensional Arrays
When the need arises to store data in multidimensional (more than twodimensional) arrays, MATLAB represents the data with additional pages. Suppose you would like to combine the following four twodimensional arrays into a threedimensional array:
x = [1,2,3;4,5,6];
y = 10*x;
z = 10*y;
w = 10*z;
You need to defi ne each page separately:
my3D_array(:,:,1) = x;
my3D_array(:,:,2) = y;
my3D_array(:,:,3) = z;
my3D_array(:,:,4) = w;
Read each of the previous statements as all the rows, all the columns, page 1, and so on. When you call up my3D_array , using the code
my3D_array
the result is
my3D_array
my3D_array(:,:,1) =
1 2 3
4 5 6
my3D_array(:,:,2) =
10 20 30
40 50 60
my3D_array(:,:,3) =
100 200 300
400 500 600
my3D_array(:,:,4) =
1000 2000 3000
4000 5000 6000
An alternative approach is to use the cat function. When you concatenate a list you group the members together in order, which is what the cat function does. The first field in the function specifies which dimension to use to concatenate the arrays, which follow in order. For example, to create the array we used in the previous example the syntax is
cat(3,x,y,z,w)
A multidimensional array can be visualized as shown in the following Figure. Even higherdimensional arrays can be created in a similar fashion.
Cell Arrays
Cell Arrays
The cell array can store different types of data inside the same array. Each element in the cell array is also an array. Refer to sets of cells by enclosing indices in smooth parentheses, (). Access the contents of cells by indexing with curly braces, {}.
Create a Cell Array
Consider the following different arrays:
X = 1:3;
Y = ['abcdefg'];
Z = single([1, 2, 3; 4, 5, 6]);
These arrays are all of a different data type and size. X is a double, Y is a char, and Z is a single. We can combine them into one cell array by using curly brackets ({}) as cellarray constructor (the standard array constructors are square brackets,[])
>> C = {X, Y, Z}
C = 1×3 cell array
{1×3 double} {'abcdefg'} {2×3 single}
Access the Element of Cell Array
Create a cell array that contains several temperature readings taken on a given date. Specify a date as a character vector, and temperatures as an array of doubles. To store these pieces of data in a cell array, enclose them in curly braces.
>> C = {'20191020', [56 67 78]}
C = 1x2 cell array
{'20170816'} {1x3 double}
Add readings for different dates to the cell array. One way to add more cells is to expand the cell array by assignment, just as you can expand an ordinary array.
>> C(2,:) = {'20191021',[58 69 79]};
>> C(3,:) = {'20191022',[60 68 81]};
>> C
C = 3x2 cell array
{'20191020'} {1x3 double}
{'20191021'} {1x3 double}
{'20191022'} {1x3 double}
Index into the first row of C. When you index with smooth parentheses, (), the result is a cell array that is a subset of the cell array.
>> C(1,:)
ans = 1x2 cell array
{'20191020'} {1x3 double}
Index into the contents of a cell. When you index with curly braces, {}, the result is the piece of data that is contained in the specified cell.
>> C{1,2}
ans = 1×3
56 67 78
Display Contents of Each Cell
Create a cell array.
>> C = {'row1',[1 2 3],3+4i;
'row2',[2 4;1 3],{'innercells',42}}
C = 2x3 cell array
{'row1'} {1x3 double} {[3.0000 + 4.0000i]}
{'row2'} {2x2 double} {1x2 cell }
Display the contents of each cell using the celldisp function. celldisp also displays the curlybrace indexing you can use to index into cells.
>> celldisp(C)
C{1,1} = row1
C{2,1} = row2
C{1,2} = 1 2 3
C{2,2} =
2 4
1 3
C{1,3} = 3.0000 + 4.0000i
C{2,3}{1} = innercells
C{2,3}{2} = 42
The last cell contains a cell array. celldisp also displays the contents of each cell from the inner cell array.
Display Different Names
Call celldisp and specify a cell array as its first input argument. Since the first argument is not a workspace variable, and so does not have a name of its own, specify a name as the second argument. celldisp displays the cell array using this name.
>> celldisp({'row1',5,10},'myCells')
myCells{1} = row1
myCells{2} = 5
myCells{3} = 10
Call celldisp without specifying a name. When there is no variable name or second input argument, celldisp displays ans as the name of the cell array.
>> celldisp({'row1',5,10})
ans{1} = row1
ans{2} = 5
ans{3} = 10
Structure Arrays
Structure Arrays
Structure arrays are similar to cell arrays. A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a field using dot notation of the form structName.fieldName.
When you have data to put into a new structure, create the structure using dot notation to name its fields one at a time:
s.a = 1;
s.b = {'A','B','C'}
s = struct with fields:
a: 1
b: {'A' 'B' 'C'}
You also can create a structure array using the struct function, described below. You can specify many fields simultaneously, or create a nonscalar structure array.
Create a Struct Array
Consider the following different arrays:
X = 1:3;
Y = ['abcdefg'];
Z = single([1, 2, 3; 4, 5, 6]);
Store related pieces of data in the fields of a structure. You can give the fields humanreadable names that describe the data. Here, we can create a simple structure by adding fields to it using dot notation.
data.numbers = X
which returns
data = struct with fields:
numbers: [1 2 3]
The name of the structure array is data. It has one field, called numbers. We can now add the content in the character matrix Y to a second field called letters:
data.letters = Y
data = struct with fields:
numbers: [1 2 3]
letters: 'abcdefg'
Finally, we add the singleprecision numbers in matrix Z to a third field called more_numbers:
data.more_numbers = Z
data = struct with fields:
numbers: [1 2 3]
letters: 'abcdefg'
more_numbers: [2×3 single]
Notice in the Workspace window that the structure matrix (called a struct) is a 1×1 array that contains all the information from all three dissimilar matrices.
We can add more content to the structure, and expand its size, by adding more matrices to the fields we’ve defined:
data(2).numbers = [1 3 5 7]
data = 1×2 struct array with fields:
numbers
letters
more_numbers
You can access the information in structure arrays by using the matrix name, field name, and index numbers. The syntax is similar to what we have used for other types of matrices. An example is
data(2)
ans = struct with fields:
numbers: [1 3 5 7]
letters: []
more_numbers: []
To access just a single field, add the field name:
data(1).numbers
ans = 1 2 3
To access the content of a particular element in a field, add the index number after the field name:
data(1).numbers(2)
ans = 2
The disp function also can be used to display the contents of structure arrays. For example:
disp(data(1).numbers(2))
returns
2
Structure arrays are of limited use in engineering calculations , but they are widely used in large computer programs to pass information between functions.
Store Related Data Variables in Structure
Create a structure by adding fields to it using dot notation. The fields contain x and yvalues for a sine wave, and text that describes the data.
data.x = linspace(0,2*pi);
data.y = sin(data.x);
data.title = 'y = sin(x)'
data = struct with fields:
x: [1×100 double]
y: [1×100 double]
title: 'y = sin(x)'
Plot the sine wave. You can refer to the arrays of x and yvalues by their field names. Then add the title.
plot(data.x,data.y)
title(data.title)
Practice Exercises 10.4
 Create a threedimensional array consisting of a 3×3 magic square, a 3×3 matrix of zeros, and a 3×3 matrix of ones.
 Use triple indexing such as A(m,n,p) to determine what number is in row 3, column 2, page 1 of the matrix you created in Exercise 1.
 Find all the values in row 2, column 3 (on all the pages) of the matrix.
 Find all the values in all the rows and pages of column 3 of the matrix.
Questions
Number Data Types
 Define an array of the first 10 integers, using the int8 type designation. Use these integers to calculate the first 10 terms in the harmonic series. The harmonic series:
$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{n} + \cdots $
Explain your results.  Explain why it is better to allow MATLAB to default to doubleprecision floatingpoint number representations for most engineering calculations than to specify single and integer types.
Character Data
 Sometimes it is confusing to realize that numbers can be represented as both numeric data and character data. Use MATLAB to express the number 85 as a character array.
 How many elements are in this array?
 What is the numeric equivalent of the character 8?
 What is the numeric equivalent of the character 5?
Character Arrays
 Create a twodimensional array called birthdays to represent the birthday of each person. For example, your array might look something like this:
birthdays=
6 11 1983
3 11 1985
6 29 1986
12 12 1984
12 11 1987 Use the num2str function to convert birthdays to a character array.
 Use the disp function to display a table of names and birthdays.
Cell Arrays
 Create a cell array called sample_cell to store the following individual arrays:
$A = \left[ {\begin{array}{*{20}{c}}1&3&5\\3&9&2\\{11}&8&2\end{array}} \right]$ (a doubleprecision floatingpoint array)
$B = \left[ {\begin{array}{*{20}{c}}{fred}&{ralph}\\{ken}&{susan}\end{array}} \right]$ (a padded character array)
$C = \left[ {\begin{array}{*{20}{c}}4\\6\\3\\1\end{array}} \right]$ (an int8 integer array) Extract array A from sample_cell.
 Extract the information in array C , row 3, from sample_cell.
 Extract the name "fred" from sample_cell . Remember that the name fred is a 1×4 array, not a single entity.
Structure Arrays
 Consider the following information about metals:
 Create the following arrays:
 Store the name of each metal into an individual character array, and store all these character arrays into a cell array.
 Store the symbol for all these metals into a single padded character array.
 Store the atomic number into an int8 integer array.
 Store the atomic weight into a doubleprecision numeric array.
 Store the density into a singleprecision numeric array.Store the structure into a single padded character array.
 Group the arrays you created in part (a) into a single structure array.
 Extract the following information from your structure array:
 Find the name, atomic weight, and structure of the fourth element in the list.
 Find the names of all the elements stored in the array.
 Find the average atomic weight of the elements in the table. (Remember, you need to extract the information to use in your calculation from the cell array.)
 Find the element with the maximum atomic weight.
 Create the following arrays: