0% found this document useful (0 votes)
5 views

141 PDFsam Matlab Prog

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

141 PDFsam Matlab Prog

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

3

Overview of MATLAB Classes


3 Overview of MATLAB Classes

Fundamental MATLAB Classes


There are many different data types, or classes, that you can work with in MATLAB. You can build
matrices and arrays of floating-point and integer data, characters and strings, logical true and
false values, and so on. Function handles connect your code with any MATLAB function regardless
of the current scope. Tables, timetables, structures, and cell arrays provide a way to store dissimilar
types of data in the same container.

There are 16 fundamental classes in MATLAB. Each of these classes is in the form of a matrix or
array. With the exception of function handles, this matrix or array is a minimum of 0-by-0 in size and
can grow to an n-dimensional array of any size. A function handle is always scalar (1-by-1).

All of the fundamental MATLAB classes are shown in the diagram below:

Numeric classes in the MATLAB software include signed and unsigned integers, and single- 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 subscripting, reshaping, and mathematical
operations.

You can create two-dimensional double and logical matrices using one of two storage formats:
full or sparse. For matrices with mostly zero-valued elements, a sparse matrix requires a fraction
of the storage space required for an equivalent full matrix. Sparse matrices invoke methods
especially tailored to solve sparse problems.

These classes require different amounts of storage, the smallest being a logical value or 8-bit
integer which requires only 1 byte. It is important to keep this minimum size in mind if you work on
data in files that were written using a precision smaller than 8 bits.

The following table describes the fundamental classes in more detail.

3-2
Fundamental MATLAB Classes

Class Name Documentation Intended Use


double, single Floating-Point • Required for fractional numeric data.
Numbers on page 4- • Double on page 4-6 and Single on page 4-6 precision.
6
• Use realmin and realmax to show range of values on page 4-
9.
• Two-dimensional arrays can be sparse.
• Default numeric type in MATLAB.
int8, uint8, Integers on page 4- • Use for signed and unsigned whole numbers.
int16, uint16, 2 • More efficient use of memory. on page 30-2
int32, uint32,
int64, uint64 • Use intmin and intmax to show range of values on page 4-
4.
• Choose from 4 sizes (8, 16, 32, and 64 bits).
char, string “Characters and • Data type for text.
Strings” • Native or Unicode®.
• Converts to/from numeric.
• Use with regular expressions on page 2-51.
• For multiple character arrays, use cell arrays.
• Starting in R2016b, you also can store text in string arrays. For
more information, see string.
logical “Logical Operations” • Use in relational conditions or to test state.
• Can have one of two values: true or false.
• Also useful in array indexing.
• Two-dimensional arrays can be sparse.
function_handle “Function Handles” • Pointer to a function.
• Enables passing a function to another function
• Can also call functions outside usual scope.
• Use to specify graphics callback functions.
• Save to MAT-file and restore later.
table, timetable “Tables”, • Tables are rectangular containers for mixed-type, column-
“Timetables” oriented data.
• Tables have row and variable names that identify contents.
• Timetables also provide storage for data in a table with rows
labeled by time. Timetable functions can synchronize, resample,
or aggregate timestamped data.
• Use the properties of a table or timetable to store metadata
such as variable units.
• Manipulation of elements similar to numeric or logical arrays.
• Access data by numeric or named index.
• Can select a subset of data and preserve the table container or
can extract the data from a table.

3-3
3 Overview of MATLAB Classes

Class Name Documentation Intended Use


struct “Structures” • Fields store arrays of varying classes and sizes.
• Access one or all fields/indices in single operation.
• Field names identify contents.
• Method of passing function arguments.
• Use in comma-separated lists on page 2-79.
• More memory required for overhead
cell “Cell Arrays” • Cells store arrays of varying classes and sizes.
• Allows freedom to package data as you want.
• Manipulation of elements is similar to numeric or logical arrays.
• Method of passing function arguments.
• Use in comma-separated lists.
• More memory required for overhead

See Also

More About
• “Valid Combinations of Unlike Classes” on page 15-2

3-4
4

Numeric Classes

• “Integers” on page 4-2


• “Floating-Point Numbers” on page 4-6
• “Create Complex Numbers” on page 4-13
• “Infinity and NaN” on page 4-14
• “Identifying Numeric Classes” on page 4-16
• “Display Format for Numeric Values” on page 4-17
• “Integer Arithmetic” on page 4-19
• “Single Precision Math” on page 4-26
4 Numeric Classes

Integers
In this section...
“Integer Classes” on page 4-2
“Creating Integer Data” on page 4-2
“Arithmetic Operations on Integer Classes” on page 4-4
“Largest and Smallest Values for Integer Classes” on page 4-4

Integer Classes
MATLAB has four signed and four unsigned integer classes. Signed types enable you to work with
negative integers as well as positive, but cannot represent as wide a range of numbers as the
unsigned types because one bit is used to designate a positive or negative sign for the number.
Unsigned types give you a wider range of numbers, but these numbers can only be zero or positive.

MATLAB supports 1-, 2-, 4-, and 8-byte storage for integer data. You can save memory and execution
time for your programs if you use the smallest integer type that accommodates your data. For
example, you do not need a 32-bit integer to store the value 100.

Here are the eight integer classes, the range of values you can store with each type, and the MATLAB
conversion function required to create that type:

Class Range of Values Conversion Function


7 7
Signed 8-bit integer -2 to 2 -1 int8
15 15
Signed 16-bit integer -2 to 2 -1 int16
31 31
Signed 32-bit integer -2 to 2 -1 int32
Signed 64-bit integer -263 to 263-1 int64
Unsigned 8-bit integer 0 to 28-1 uint8
16
Unsigned 16-bit integer 0 to 2 -1 uint16
32
Unsigned 32-bit integer 0 to 2 -1 uint32
64
Unsigned 64-bit integer 0 to 2 -1 uint64

Creating Integer Data


MATLAB stores numeric data as double-precision floating point (double) by default. To store data as
an integer, you need to convert from double to the desired integer type. Use one of the conversion
functions shown in the table above.

For example, to store 325 as a 16-bit signed integer assigned to variable x, type
x = int16(325);

If the number being converted to an integer has a fractional part, MATLAB rounds to the nearest
integer. If the fractional part is exactly 0.5, then from the two equally nearby integers, MATLAB
chooses the one for which the absolute value is larger in magnitude:
x = 325.499;
int16(x)

4-2
Integers

ans =

int16

325

x = x + .001;
int16(x)
ans =

int16

326

If you need to round a number using a rounding scheme other than the default, MATLAB provides
four rounding functions: round, fix, floor, and ceil. The fix function enables you to override the
default and round towards zero when there is a nonzero fractional part:
x = 325.9;

int16(fix(x))
ans =

int16

325

Arithmetic operations that involve both integers and floating-point always result in an integer data
type. MATLAB rounds the result, when necessary, according to the default rounding algorithm. The
example below yields an exact answer of 1426.75 which MATLAB then rounds to the next highest
integer:
int16(325) * 4.39
ans =

int16

1427

The integer conversion functions are also useful when converting other classes, such as strings, to
integers:
str = 'Hello World';

int8(str)
ans =

1×11 int8 row vector

72 101 108 108 111 32 87 111 114 108 100

If you convert a NaN value into an integer class, the result is a value of 0 in that integer class. For
example,
int32(NaN)
ans =

int32

4-3
4 Numeric Classes

Arithmetic Operations on Integer Classes


MATLAB can perform integer arithmetic on the following types of data:

• Integers or integer arrays of the same integer data type. This yields a result that has the same
data type as the operands:

x = uint32([132 347 528]) .* uint32(75);


class(x)
ans =
uint32
• Integers or integer arrays and scalar double-precision floating-point numbers. This yields a result
that has the same data type as the integer operands:

x = uint32([132 347 528]) .* 75.49;


class(x)
ans =
uint32

For all binary operations in which one operand is an array of integer data type (except 64-bit
integers) and the other is a scalar double, MATLAB computes the operation using element-wise
double-precision arithmetic, and then converts the result back to the original integer data type. For
binary operations involving a 64-bit integer array and a scalar double, MATLAB computes the
operation as if 80-bit extended-precision arithmetic were used, to prevent loss of precision.

Operations involving complex numbers with integer types is not supported.

Largest and Smallest Values for Integer Classes


For each integer data type, there is a largest and smallest number that you can represent with that
type. The table shown under “Integers” on page 4-2 lists the largest and smallest values for each
integer data type in the “Range of Values” column.

You can also obtain these values with the intmax and intmin functions:

intmax('int8')
ans =

int8

127

intmin('int8')
ans =

int8

-128

If you convert a number that is larger than the maximum value of an integer data type to that type,
MATLAB sets it to the maximum value. Similarly, if you convert a number that is smaller than the
minimum value of the integer data type, MATLAB sets it to the minimum value. For example,

4-4
Integers

x = int8(300)
x =

int8

127

x = int8(-300)
x =

int8

-128

Also, when the result of an arithmetic operation involving integers exceeds the maximum (or
minimum) value of the data type, MATLAB sets it to the maximum (or minimum) value:

x = int8(100) * 3
x =

int8

127

x = int8(-100) * 3
x =

int8

-128

4-5
4 Numeric Classes

Floating-Point Numbers
In this section...
“Double-Precision Floating Point” on page 4-6
“Single-Precision Floating Point” on page 4-6
“Creating Floating-Point Data” on page 4-6
“Arithmetic Operations on Floating-Point Numbers” on page 4-8
“Largest and Smallest Values for Floating-Point Classes” on page 4-9
“Accuracy of Floating-Point Data” on page 4-10
“Avoiding Common Problems with Floating-Point Arithmetic” on page 4-11

MATLAB represents floating-point numbers in either double-precision or single-precision format. The


default is double precision, but you can make any number single precision with a simple conversion
function.

Double-Precision Floating Point


MATLAB constructs the double-precision (or double) data type according to IEEE® Standard 754 for
double precision. Any value stored as a double requires 64 bits, formatted as shown in the table
below:

Bits Usage
63 Sign (0 = positive, 1 = negative)
62 to 52 Exponent, biased by 1023
51 to 0 Fraction f of the number 1.f

Single-Precision Floating Point


MATLAB constructs the single-precision (or single) data type according to IEEE Standard 754 for
single precision. Any value stored as a single requires 32 bits, formatted as shown in the table
below:

Bits Usage
31 Sign (0 = positive, 1 = negative)
30 to 23 Exponent, biased by 127
22 to 0 Fraction f of the number 1.f

Because MATLAB stores numbers of type single using 32 bits, they require less memory than
numbers of type double, which use 64 bits. However, because they are stored with fewer bits,
numbers of type single are represented to less precision than numbers of type double.

Creating Floating-Point Data


Use double-precision to store values greater than approximately 3.4 x 1038 or less than approximately
-3.4 x 1038. For numbers that lie between these two limits, you can use either double- or single-
precision, but single requires less memory.

4-6
Floating-Point Numbers

Creating Double-Precision Data

Because the default numeric type for MATLAB is double, you can create a double with a simple
assignment statement:
x = 25.783;

The whos function shows that MATLAB has created a 1-by-1 array of type double for the value you
just stored in x:
whos x
Name Size Bytes Class

x 1x1 8 double

Use isfloat if you just want to verify that x is a floating-point number. This function returns logical
1 (true) if the input is a floating-point number, and logical 0 (false) otherwise:
isfloat(x)
ans =

logical

You can convert other numeric data, characters or strings, and logical data to double precision using
the MATLAB function, double. This example converts a signed integer to double-precision floating
point:
y = int64(-589324077574); % Create a 64-bit integer

x = double(y) % Convert to double


x =
-5.8932e+11

Creating Single-Precision Data

Because MATLAB stores numeric data as a double by default, you need to use the single
conversion function to create a single-precision number:
x = single(25.783);

The whos function returns the attributes of variable x in a structure. The bytes field of this structure
shows that when x is stored as a single, it requires just 4 bytes compared with the 8 bytes to store it
as a double:
xAttrib = whos('x');
xAttrib.bytes
ans =
4

You can convert other numeric data, characters or strings, and logical data to single precision using
the single function. This example converts a signed integer to single-precision floating point:
y = int64(-589324077574); % Create a 64-bit integer

x = single(y) % Convert to single


x =

4-7
4 Numeric Classes

single

-5.8932e+11

Arithmetic Operations on Floating-Point Numbers


This section describes which classes you can use in arithmetic operations with floating-point
numbers.

Double-Precision Operations

You can perform basic arithmetic operations with double and any of the following other classes.
When one or more operands is an integer (scalar or array), the double operand must be a scalar. The
result is of type double, except where noted otherwise:

• single — The result is of type single


• double
• int* or uint* — The result has the same data type as the integer operand
• char
• logical

This example performs arithmetic on data of types char and double. The result is of type double:

c = 'uppercase' - 32;

class(c)
ans =
double

char(c)
ans =
UPPERCASE

Single-Precision Operations

You can perform basic arithmetic operations with single and any of the following other classes. The
result is always single:

• single
• double
• char
• logical

In this example, 7.5 defaults to type double, and the result is of type single:

x = single([1.32 3.47 5.28]) .* 7.5;

class(x)
ans =
single

4-8
Floating-Point Numbers

Largest and Smallest Values for Floating-Point Classes


For the double and single classes, there is a largest and smallest number that you can represent
with that type.

Largest and Smallest Double-Precision Values

The MATLAB functions realmax and realmin return the maximum and minimum values that you
can represent with the double data type:

str = 'The range for double is:\n\t%g to %g and\n\t %g to %g';


sprintf(str, -realmax, -realmin, realmin, realmax)

ans =
The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308

Numbers larger than realmax or smaller than -realmax are assigned the values of positive and
negative infinity, respectively:

realmax + .0001e+308
ans =
Inf

-realmax - .0001e+308
ans =
-Inf

Largest and Smallest Single-Precision Values

The MATLAB functions realmax and realmin, when called with the argument 'single', return the
maximum and minimum values that you can represent with the single data type:

str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';


sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))

ans =
The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38

Numbers larger than realmax('single') or smaller than -realmax('single') are assigned the
values of positive and negative infinity, respectively:

realmax('single') + .0001e+038
ans =

single

Inf

-realmax('single') - .0001e+038
ans =

single

4-9
4 Numeric Classes

-Inf

Accuracy of Floating-Point Data


If the result of a floating-point arithmetic computation is not as precise as you had expected, it is
likely caused by the limitations of your computer's hardware. Probably, your result was a little less
exact because the hardware had insufficient bits to represent the result with perfect accuracy;
therefore, it truncated the resulting value.

Double-Precision Accuracy

Because there are only a finite number of double-precision numbers, you cannot represent all
numbers in double-precision storage. On any computer, there is a small gap between each double-
precision number and the next larger double-precision number. You can determine the size of this
gap, which limits the precision of your results, using the eps function. For example, to find the
distance between 5 and the next larger double-precision number, enter

format long

eps(5)
ans =
8.881784197001252e-16

This tells you that there are no double-precision numbers between 5 and 5 + eps(5). If a double-
precision computation returns the answer 5, the result is only accurate to within eps(5).

The value of eps(x) depends on x. This example shows that, as x gets larger, so does eps(x):

eps(50)
ans =
7.105427357601002e-15

If you enter eps with no input argument, MATLAB returns the value of eps(1), the distance from 1
to the next larger double-precision number.

Single-Precision Accuracy

Similarly, there are gaps between any two single-precision numbers. If x has type single, eps(x)
returns the distance between x and the next larger single-precision number. For example,

x = single(5);
eps(x)

returns

ans =

single

4.7684e-07

Note that this result is larger than eps(5). Because there are fewer single-precision numbers than
double-precision numbers, the gaps between the single-precision numbers are larger than the gaps
between double-precision numbers. This means that results in single-precision arithmetic are less
precise than in double-precision arithmetic.

4-10
Floating-Point Numbers

For a number x of type double, eps(single(x)) gives you an upper bound for the amount that x is
rounded when you convert it from double to single. For example, when you convert the double-
precision number 3.14 to single, it is rounded by
double(single(3.14) - 3.14)
ans =
1.0490e-07

The amount that 3.14 is rounded is less than


eps(single(3.14))
ans =

single

2.3842e-07

Avoiding Common Problems with Floating-Point Arithmetic


Almost all operations in MATLAB are performed in double-precision arithmetic conforming to the
IEEE standard 754. Because computers only represent numbers to a finite precision (double precision
calls for 52 mantissa bits), computations sometimes yield mathematically nonintuitive results. It is
important to note that these results are not bugs in MATLAB.

Use the following examples to help you identify these cases:

Example 1 — Round-Off or What You Get Is Not What You Expect

The decimal number 4/3 is not exactly representable as a binary fraction. For this reason, the
following calculation does not give zero, but rather reveals the quantity eps.
e = 1 - 3*(4/3 - 1)

e =
2.2204e-16

Similarly, 0.1 is not exactly representable as a binary number. Thus, you get the following
nonintuitive behavior:
a = 0.0;
for i = 1:10
a = a + 0.1;
end
a == 1
ans =

logical

Note that the order of operations can matter in the computation:


b = 1e-16 + 1 - 1e-16;
c = 1e-16 - 1e-16 + 1;
b == c
ans =

4-11
4 Numeric Classes

logical

There are gaps between floating-point numbers. As the numbers get larger, so do the gaps, as
evidenced by:

(2^53 + 1) - 2^53

ans =
0

Since pi is not really π, it is not surprising that sin(pi) is not exactly zero:

sin(pi)

ans =
1.224646799147353e-16

Example 2 — Catastrophic Cancellation

When subtractions are performed with nearly equal operands, sometimes cancellation can occur
unexpectedly. The following is an example of a cancellation caused by swamping (loss of precision
that makes the addition insignificant).

sqrt(1e-16 + 1) - 1

ans =
0

Some functions in MATLAB, such as expm1 and log1p, may be used to compensate for the effects of
catastrophic cancellation.

Example 3 — Floating-Point Operations and Linear Algebra

Round-off, cancellation, and other traits of floating-point arithmetic combine to produce startling
computations when solving the problems of linear algebra. MATLAB warns that the following matrix A
is ill-conditioned, and therefore the system Ax = b may be sensitive to small perturbations:

A = diag([2 eps]);
b = [2; eps];
y = A\b;
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-16.

These are only a few of the examples showing how IEEE floating-point arithmetic affects
computations in MATLAB. Note that all computations performed in IEEE 754 arithmetic are affected,
this includes applications written in C or FORTRAN, as well as MATLAB.

References
[1] Moler, Cleve. “Floating Points.” MATLAB News and Notes. Fall, 1996.

[2] Moler, Cleve. Numerical Computing with MATLAB. Natick, MA: The MathWorks, Inc., 2004.

4-12
Create Complex Numbers

Create Complex Numbers


Complex numbers consist of two separate parts: a real part and an imaginary part. The basic
imaginary unit is equal to the square root of -1. This is represented in MATLAB by either of two
letters: i or j.

The following statement shows one way of creating a complex value in MATLAB. The variable x is
assigned a complex number with a real part of 2 and an imaginary part of 3:

x = 2 + 3i;

Another way to create a complex number is using the complex function. This function combines two
numeric inputs into a complex output, making the first input real and the second imaginary:

x = rand(3) * 5;
y = rand(3) * -8;

z = complex(x, y)
z =
4.7842 -1.0921i 0.8648 -1.5931i 1.2616 -2.2753i
2.6130 -0.0941i 4.8987 -2.3898i 4.3787 -3.7538i
4.4007 -7.1512i 1.3572 -5.2915i 3.6865 -0.5182i

You can separate a complex number into its real and imaginary parts using the real and imag
functions:

zr = real(z)
zr =
4.7842 0.8648 1.2616
2.6130 4.8987 4.3787
4.4007 1.3572 3.6865

zi = imag(z)
zi =
-1.0921 -1.5931 -2.2753
-0.0941 -2.3898 -3.7538
-7.1512 -5.2915 -0.5182

4-13
4 Numeric Classes

Infinity and NaN


In this section...
“Infinity” on page 4-14
“NaN” on page 4-14

Infinity
MATLAB represents infinity by the special value Inf. Infinity results from operations like division by
zero and overflow, which lead to results too large to represent as conventional floating-point values.
MATLAB also provides a function called Inf that returns the IEEE arithmetic representation for
positive infinity as a double scalar value.

Several examples of statements that return positive or negative infinity in MATLAB are shown here.

x = 1/0 x = 1.e1000
x = x =
Inf Inf
x = exp(1000) x = log(0)
x = x =
Inf -Inf

Use the isinf function to verify that x is positive or negative infinity:

x = log(0);

isinf(x)
ans =
1

NaN
MATLAB represents values that are not real or complex numbers with a special value called NaN,
which stands for “Not a Number”. Expressions like 0/0 and inf/inf result in NaN, as do any
arithmetic operations involving a NaN:

x = 0/0
x =

NaN

You can also create NaNs by:

x = NaN;

whos x
Name Size Bytes Class

x 1x1 8 double

The NaN function returns one of the IEEE arithmetic representations for NaN as a double scalar
value. The exact bit-wise hexadecimal representation of this NaN value is,

4-14
Infinity and NaN

format hex
x = NaN

x =

fff8000000000000

Always use the isnan function to verify that the elements in an array are NaN:

isnan(x)
ans =

MATLAB preserves the “Not a Number” status of alternate NaN representations and treats all of the
different representations of NaN equivalently. However, in some special cases (perhaps due to
hardware limitations), MATLAB does not preserve the exact bit pattern of alternate NaN
representations throughout an entire calculation, and instead uses the canonical NaN bit pattern
defined above.

Logical Operations on NaN

Because two NaNs are not equal to each other, logical operations involving NaN always return false,
except for a test for inequality, (NaN ~= NaN):

NaN > NaN


ans =
0

NaN ~= NaN
ans =
1

4-15
4 Numeric Classes

Identifying Numeric Classes


You can check the data type of a variable x using any of these commands.

Command Operation
whos x Display the data type of x.
xType = class(x); Assign the data type of x to a variable.
isnumeric(x) Determine if x is a numeric type.
isa(x, 'integer') Determine if x is the specified numeric type. (Examples for any
isa(x, 'uint64') integer, unsigned 64-bit integer, any floating point, double precision,
isa(x, 'float') and single precision are shown here).
isa(x, 'double')
isa(x, 'single')
isreal(x) Determine if x is real or complex.
isnan(x) Determine if x is Not a Number (NaN).
isinf(x) Determine if x is infinite.
isfinite(x) Determine if x is finite.

4-16

You might also like