Lesson 10: Other Kinds of Arrays
Objective
- 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 single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision 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 single-precision. Integer and single precision arrays offer more memory-efficient storage than double precision.
All numeric types support basic array operations, such as indexing, reshaping, and mathematical operations.
Create Numeric Variables
Syntax | Function | Description |
---|---|---|
y = double(x) | Double-precision arrays (64-bit) | Converts the values in x to double precision. |
y = single(x) | Single-precision arrays (32-bit) | Converts the values in x to single precision. |
y = int8(x) | 8-bit signed integer arrays | Converts the values in x to type int8. Values outside the range [-27, 27-1] map to the nearest endpoint. |
y = int16(x) | 16-bit signed integer arrays | Converts the values in x to type int16. Values outside the range [-215, 215-1] map to the nearest endpoint. |
y = int32(x) | 32-bit signed integer arrays | Converts the values in x to type int32. Values outside the range [-231, 231-1] map to the nearest endpoint. |
y = int64(x) | 64-bit signed integer arrays | Converts the values in x to type int64. Values outside the range [-263, 263-1] map to the nearest endpoint. |
y = uint8(x) | 8-bit unsigned integer arrays | Converts the values in x to type uint8. Values outside the range [0, 28-1] map to the nearest endpoint. |
y = uint16(x) | 16-bit unsigned integer arrays | Converts the values in x to type uint16. Values outside the range [0, 216-1] map to the nearest endpoint. |
y = uint32(x) | 32-bit unsigned integer arrays | Converts the values in x to type uint32. Values outside the range [0, 232-1] map to the nearest endpoint. |
y = uint64(x) | 64-bit unsigned integer arrays | Converts the values in x to type uint64. Values outside the range [0, 264-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 8-bit signed integer array
Variables in MATLAB of data type (class) int8 are stored as 1×8 (8-bit) 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 16-bit 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 16-bytes storage room, because both the real and imaginary components must be stored. If convert complex numbers to int8, it needs 2 byte (16-bit) 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
Single-precision floating-point numbers use only half the storage space of a double-precision number and thus store only half the information. Each value requires only 4 bytes, or 4 × 8 = 32 bits, of storage space. Since single-precision numbers are allocated only half as much storage space, they cannot cover as large a range of values as double-precision numbers. It will make round-off 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 double-double precision floating-point 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 built-in 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 floating-point number to an integer, the cast function rounds the number to the nearest integer. If the floating-point 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 Numeric Data Type
Convert an int8 value to uint8.
% Define a scalar 8-bit integer.
a = int8(5);
% Convert a to an unsigned 8-bit integer.
b = cast(a, 'uint8');
class(b)
In the Command Window, you will see:
ans = 'uint8'
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 1
Converts between data types of the same size
>> typecast(uint8(255), 'int8')
ans = uint8 -1
>> typecast(int16(-1), 'uint16')
ans = uint16 65535
Example 2
Set X to a 1×3 vector of 32-bit integers, then cast it to an 8-bit integer type:
>> X = uint32([1 255 256])
X = 1 255 256
Running this on a little-endian system produces the following results. Each 32-bit value is divided up into four 8-bit 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 big-endian system. The four 8-bit segments of the input data are combined to produce two 16-bit segments
>> Y = typecast(X, 'uint16')
Y = 2c37 424d
The second is done on a little-endian system. Note the difference in byte ordering:
>> Y = typecast(X, 'uint16')
Y = 372c 4d42
You can format the little-endian output into big-endian (and vice versa) using the swapbytes function:
>> Y = swapbytes(typecast(X, 'uint16'))
Y = 2c37 424d
Example 4
This example attempts to make a 32-bit value from a vector of three 8-bit 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 8-bit 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 floating-point 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 double-precision 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 8-bit 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 'UTF-8', 'latin1', 'US-ASCII', 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 'UTF-8', 'latin1', 'US-ASCII', 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 floating-point 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 double-precision number | Where S contains 16 characters representing a hexadecimal number, returns the IEEE double-precision floating-point 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 floating-point 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,'dd-MMM-yyyy','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 dim1Dist,...dimNDist 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 floating-point 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'
Padded Character Arrays
Convert multiple character arrays into two padded character arrays, C, D.
A1 = 'Apple';
A2 = 'IBM';
A3 = 'CalStateLA';
C = char(A1, A2, A3)
D = [char(A1, A2)]
C = 3×10 char array
'Apple '
'IBM '
'CalStateLA'
D = 2×5 char array
'Apple'
'IBM '
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 floating-point array | Returns true if A is a floating-point array and false otherwise. The floating-point 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 two-dimensional 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 two-dimensional array that has a size of 1×N or N×1, where N is a non-negative 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 MAT-file. | |
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
Floating-point relative accuracy
Syntax | Description |
---|---|
d = eps | Returns the distance from 1.0 to the next larger double-precision 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 floating-point 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 floating-point format
Syntax | Description |
---|---|
f = flintmax | Returns the largest consecutive integer in IEEE double precision, which is 253. Above this value, double-precision 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 (224) for single precision and 253 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 double-precision, Inf represents numbers larger than realmax. For single-precision, Inf represents numbers larger than realmax('single'). |
X = Inf(n) | Returns an n×n matrix of Inf values. |
X = Inf(sz1,...,szN) | Returns an sz1×...×szN array of Inf values, where sz1,...,szN 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 32-bit 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 32-bit integer. Any value smaller than the value returned by intmin saturates to the intmin value when cast to a 32-bit 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 sz1×...×szN array of NaN values, where sz1,...,szN 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 floating-point number
Syntax | Description |
---|---|
f = realmax | Returns the largest finite floating-point number in IEEE double precision. This is equal to (2-2-52)*21023. |
f = realmax(precision) | Returns the largest finite floating-point number in IEEE single or double precision. This is equal to realmax for double precision, and to single ((2-2-23)*2127) for single precision. |
Smallest normalized floating-point number
Syntax | Description |
---|---|
f = realmin | Returns the smallest positive normalized floating-point number in IEEE double precision. This is equal to 2-1022. |
f = realmin(precision) | Returns the smallest positive normalized floating-point 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]\)
- Double-precision floating point — name this array A
- Single-precision floating point — name this array B
- 16-bit singed-integer — name this array C
- 32-bit 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 two-dimensional 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 Numeric Array
>> A = [77 65 84 76 65 66];
>> str = string(A)
str = 1x6 string array
"77" "65" "84" "76" "65" "66"
str is a string array in which each element represents a number from A. Note that string does not treat numbers as ASCII or Unicode values the way that the char function does.
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.9e-3"]
>> 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 floating-point 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 double-precision 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)-by-max(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 8-bytes storage room, This matrix uses 800-megabytes 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.25-megabytes of memory. In this case, you can avoid full storage completely by using the speye function, which creates sparse identity matrices directly.
Sparse Matrix of All Zeros
>> S = sparse(10000,5000)
S = All zero sparse: 10000×5000
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 name-value 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' name-value 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','d-MMM-y HH:mm:ss Z')
t = datetime
22-Oct-2019 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','d-MMM-y HH:mm:ss Z')
t = datetime
22-Oct-2019 15:37:24 +0800
Date and Time from Character Vectors
Create a datetime array from a cell array of character vectors.
>> DateStrings = {'2014-05-26';'2014-08-03'};
>> t = datetime(DateStrings,'InputFormat','yyyy-MM-dd')
t = 2×1 datetime array
26-May-2014
03-Aug-2014
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 yyyy-MM-dd. The format must be specified as a character vector, even though str is a string array.
>> str = string({'2016-03-24','2016-04-19'});
>> t = datetime(str,'InputFormat','yyyy-MM-dd')
t = 1×2 datetime array
24-Mar-2016 19-Apr-2016
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' name-value pair argument.
>> d = '2018-06-25 11:23:37.712';
>> t = datetime(d,'InputFormat','yyyy-MM-dd HH:mm:ss.SSS')
t = datetime
25-Jun-2018 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' name-value 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
31-Jan-2014
30-Jan-2013
31-Jan-2012
Specify a custom display format for the output, using the Format name-value 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 two-dimensional) arrays, MATLAB represents the data with additional pages. Suppose you would like to combine the following four two-dimensional arrays into a three-dimensional 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 higher-dimensional 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 cell-array 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 = {'2019-10-20', [56 67 78]}
C = 1x2 cell array
{'2017-08-16'} {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,:) = {'2019-10-21',[58 69 79]};
>> C(3,:) = {'2019-10-22',[60 68 81]};
>> C
C = 3x2 cell array
{'2019-10-20'} {1x3 double}
{'2019-10-21'} {1x3 double}
{'2019-10-22'} {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
{'2019-10-20'} {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 curly-brace 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 human-readable 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 single-precision 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.
Practice Exercises 10.4
- Create a three-dimensional 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 double-precision floating-point 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 two-dimensional 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 double-precision floating-point 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 double-precision numeric array.
- Store the density into a single-precision 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: