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

BasicMDL 3 NumMatrices

The document discusses working with numbers and matrices in MATLAB. It covers numeric data types like integers, floating-point numbers, complex numbers, and special values. It also discusses generating numeric sequences using colon operators, linspace, logspace and freqspace functions. The document discusses generating random numbers using rand, randi and randn functions. It covers basic matrix operations like concatenation and indexing into matrices.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

BasicMDL 3 NumMatrices

The document discusses working with numbers and matrices in MATLAB. It covers numeric data types like integers, floating-point numbers, complex numbers, and special values. It also discusses generating numeric sequences using colon operators, linspace, logspace and freqspace functions. The document discusses generating random numbers using rand, randi and randn functions. It covers basic matrix operations like concatenation and indexing into matrices.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Working with Numbers and Matrices

Dominic C. Ezugworie
[email protected]
+234 (0) 703 907 1904

© 2012 Dominic C. Ezugworie


Sort of Introduction
• MATLAB has extensive library of functions for
mathematical computations
• Your use of MATLAB for any field is limited by
the extent of your knowledge of the subject
• Proficiency in MATLAB lies in the manipulation
of matrices

2
Here we go ...
• Numeric Data Types
– Integers (signed and unsigned)
– Floating-point numbers ( single and double )
– Complex numbers
– inf and NaN
• Working with Matrices (Matrices 2)
– Generating numeric and random sequences
– Concatenation of matrices
– Getting info about a matrix
– Indexing into matrices
3
Numeric Data Types
• Signed and unsigned integers,
Single- and double-precision floating-point numbers.

• Default data type: double-precision floating point.


– (You cannot change the default type and precision.)
• Integer and single-precision arrays offer more
memory-efficient storage than double-precision.

• All numeric types support basic array operations

4
Integers
• You can save
memory and
execution time for
your programs if
you use the
smallest integer
type that
accommodates
your data.

• For example, you


don't need a 32-bit
integer to store the
value 100.

5
Integers
• Create an integer – a form of conversion
y = int16(325);
x = 325.499; y = int16(x)
• The result of arithmetic operations on integers
is the same type as the integer operand
int16(325) * 4.39
str = 'Hello World'; int8(str)
• Largest and smallest value
intmax(‘int_type’)
intmin(‘int_type’)

6
Floating-Point Numbers
• Floating-point numbers constructed according
to the IEEE standard 754
• They are used to store numbers larger than
intmax(‘uint64’)
• Double precision data type requires 64 bits
• Single precision data type requires 32 bits
• Single precision -> less memory, less precision

7
Floating-Point Numbers
• Creating floating-point numbers
– Constructed by default as double precision
X = 34.676959

– Use the conversion functions


y = int64(-589324077574); % Create a 64-bit integer
x1 = double(y) % Convert to double
x2 = single(25.783) % Convert to single

8
Floating-Point Numbers
• Arithmetic Operations on Double precision Numbers
– the result is always double except for single data
type and integer data types
• c = 'uppercase' - 32;
class(c),
char(c)
• x = single([1.32 3.47 5.28]) .* 7.5;
class(x)

• The Largest and Smallest Values supported by your machine


is determined by
realmax(‘data_type’), realmin(‘data_type’)

9
Accuracy of Floating-Point Data
• Accuracy is limited by a small gap between
each double-precision number and the next
larger double-precision number. –
eps(5) % nothing between 5 and 5 + eps(5)
eps(single(5))
• eps(x) depends on x, increases as x gets
larger

10
Accuracy of Floating-Point Data
• Round off or what you get is not what you
expect
– Numbers not exactly representable by bits
e = 1 - 3*(4/3 - 1)
p = 0.0; p = p + 0.1 % repeat 10 times
p == 1 % then checkout this
– eps(x) gets larger as x increases
(2^53 + 1) - 2^53 % what is eps(2^53) ?
– pi is not really pi
sin(pi)

11
Accuracy of Floating-Point Data
• Catastrophic cancellation
– Performing subtractions with nearly equal
operands
sqrt(1e-16 + 1) - 1
• Floating point operations on linear algebra
A = diag([2 eps]); b = [2; eps];
y = A\b;
• Thus, all IEEE 754 arithmetic computations are
affected even in C and FORTRAN languages
12
Complex Numbers
• Two separate parts:
– a real part and an imaginary part.
• The basic imaginary unit = sqrt(-1)
– Represented by either of two letters: i or j.
• Created specifically
z = a + bi
• Or using the complex function
z = complex(a, b)% => z = a + bi
• Seperated by real(z) and imag(z) functions

13
Infinity and NaN
• Operations leading to Numbers larger than that
representable by conventional floating-point values =
inf or –inf as the case may be.
• Examples:
x = 1/0, x = 1.e1000, x = exp(1000),
x = log(0)
• NaN = Not a Number
– values that are not real or complex numbers
x = 7i/0

14
Identifying Numeric Classes

15
Next Stage ...
 Numeric Data Types
 Working with Matrices (Matrices 2)
 Generating numeric sequences
 Generating random numbers
 Concatenation of matrices
 Getting info about a matrix
 Indexing into matrices

16
What are Matrices?
Recall the Module 2 Matrices 1 topic ?
• Rectangular array of numbers
• The most basic way of storing data in MATLAB
• Can have the forms of:
 Null = empty matrix; e.g. X = [];
 Scalar = 1-by-1 matrix; e.g. A = 56;
 Vector = only one row or only one column
e.g. sales = [ 34.5, 15, 84, 0.0];
 Rectangular = m-by-n matrix
17
Working with Matrices
• Your array of data can be empirical
– Data gathered from empirical/experimental
studies
– Can be imported from excel, notepad, etc
• Or mathematically generated
– Using Numeric sequence and Matrix generation
techniques
– Mathematical formulas can be involved

18
Generating Numeric Sequences
• Using the colon operator
– Specify the sequence as a range of values
– Stating the start and end values
datarange = startvalue:endvalue
dtrg1 = 0:5; % integers from 0 to 5
dtrg2 = -10:10; % how many elements?

• The default step size is 1

19
Generating Numeric Sequences
• You can also specify the step size
% numeric sequence from 4 to 90
% with step size of 8
seq1 = 4:8:90;
• The step size can be fractional
seq2 = 0:0.5:10;
• The step can also be negative
seq3 = 20:-2:0;
% count backwards to 0 from 20
% with 2 as step size

20
Generating Numeric Sequences
• The linspace function
– generates linearly spaced vectors
– Gives direct control over the number of points
linspace(a,b) % generates a row vector of
% 100 points linearly spaced
between % and including a and b.

linspace(a,b,n) % generates a row vector of


% n points linearly spaced between
% and including a and b.

21
Generating Numeric Sequences
• The logspace function
– generates logarithmically spaced vectors
– Useful for creating frequency vectors
logspace(a,b) % generates a row vector of
% 50 points logarithmically spaced between
% and including decades 10^a and 10^b.

logspace(a,b,n) % generates n points between


% and including decades 10^a and 10^b.

logspace(a,pi) % generates n points between


% and including decades 10^a and 10^b.
22
Generating Numeric Sequences
The linspace and logspace functions
• The generated sequence can be decreasing
• Examples
linspace(40,25,16); % same as 40:-1:25

logspace(a,pi) % generates n points between


% and including decades 10^a and pi, which
is useful for digital signal processing where
frequencies over this interval go around the unit
circle

23
Generating Numeric Sequences
• The freqspace function
– generates equally spaced frequency vectors
– Frequency spacing used for frequency responses
[f1,f2] = freqspace(n)
% returns the 2-D frequency vectors f1 and
% f2 for an n-by-n matrix
[f1,f2] = freqspace(a,b)
% returns the 2-D frequency vectors f1 and
% f2 for an a-by-b matrix

>> doc freqspace % for more information


24
Generating Random Numbers
Use the functions: rand, randi, randn
– rand % most common function
– E.g. rand(2,3) % generates a
% 2-by-3 array of random numbers
• rand generates numbers between 0 and 1
(inclusive)
• rand generates a pseudorandom value
drawn from the standard uniform distribution

25
Generating Random Numbers
Syntax Returns
• rand % a scalar
• rand(n) % an n-by-n matrix
• rand(m,n) % an m-by-n matrix
• rand([m,n]) % an m-by-n matrix
• rand(m,n,p,...) % a higher dimension array
• rand(size(A)) % an array same size as A
• rand(..., 'double‘)
% array of double data type
• rand(..., 'single')
% array of single precision
26
Generating Random Numbers
For random integers: randi(imax)
• randi generates a pseudorandom integer value
drawn from the discrete uniform distribution
– rand(imax) % generates a random %
integer on the range 1:imax
• Similar syntax as the rand function but must
contain imax or [imin imax] as the
first argument

27
Generating Random Numbers
Generate numbers Within a range
r = b.*rand; % e.g. 10*rand(3,4);
% generates random
% values on the range [0, b]
r = a + (b-a).*rand(100,1);
% generates random
% values on the range [a, b]
randi([imin, imax]) % generates a random
% integer on the range imin:imax

28
Dimensions of a Matrix
• Consider an [m x n] i.e. [m-by-n] array
– First dimension = m, i.e. row-wise
– Second dimension = n, i.e. column-wise
• Consider an [m x n x p] i.e. [m-by-n-by-p] array
– Third dimension = p, i.e. page-wise
– Illustrated in next slide
• Higher dimensions – block-wise

29
A typical 3-D array

30
Concatenation of Matrices
• Combine matrices along desired dimensions
• Creating a matrix is a form of concatenation
• Example of a scalar: a = 4; % 1 x 1 array
• Example of a row vector:
b = [3,9,5,4]; % 4 x 1 array
• Example of a column vector: % 1 x 4 array
c1 = [4;5;9;3]; % or c2 = [4,5,9,3]’;

31
Concatenation of Matrices
Using the matrix operator
• Given the matrices 3 6 8 1 6 1
A  B 
 7 2 4  9 3 4 
• Concatenate along the first dimension
– Increase the number of rows
C1 = [A; B]
• Concatenate along the second dimension
– Increase the number of columns
C2 = [A, B]
32
Concatenation of Matrices
Using the vertical and horizontal concatenation
functions
•Concatenate along the first dimension
– Increase the number of rows
C1 = vertcat(A, B)
•Concatenate along the second dimension
– Increase the number of columns
C2 = horzcat(A, B)

33
Concatenation of Matrices
Using the general concatenation function
C = cat(dim, A, B) % dim = dimension
• Concatenate along the first dimension
– Increase the number of rows
C1 = cat(1, A, B)
• Concatenate along the second dimension
– Increase the number of columns
C2 = cat(2, A, B)

34
Concatenation of Matrices
Using the general concatenation function
C = cat(dim, A, B) % dim = dimension
• Concatenate along a higher dimension
C3 = cat(3, A, B)
C4 = cat(4, A, B)

35
Concatenation of Matrices
• Concatenating more than two matrices
A = [4,5,6;7,3,1]; B = [5,9,3;8,2,1];
C = 4*rand(2,4); D = 2*ones(1,3);
• Vertically
abcd1 = [A;B;D]
• Horizontally
abcd2 = [A,B,C];

• Other concatenation functions still apply

36
Concatenation of Matrices
• Concatenating more than two matrices
A = [4,5,6;7,3,1]; B = [5,9,3;8,2,1];
C = 4*rand(2,4); D = 2*ones(1,3);

• NB:
– Resulting Matrix must be rectangular!
– Matrices must match along the cat dimension
c = cat(2,A,B,D) % ERROR!

37
Concatenation of Matrices
• Replicating a matrix
• repmat(A, v, h)
– replicates input matrix A, v times vertically and h
times horizontally
Matrix A

38
Your turn
• Generate the checkerboard pattern
• Hint: use the identity matrix

39
On the Journey...
 Working with Matrices (Matrices 2)
 Generating numeric sequences
 Concatenation of matrices
 Getting info about a matrix
 Indexing

40
Getting info about a matrix
• Dimensions of a matrix: d = size(A)
– the sizes of each dimension of array A are
returned in a vector d
• Number of array dimensions: n = ndims(A)
• Number of elements in array: n = numel(A)
• Length of largest array dimension:
n = length(A)
– finds the number of elements along the largest dimension
of an array
– Same as the number of elements in a vector
41
Getting info about a matrix
Data Structures Used in the Matrix

42
Indexing into Matrices
• One of the core stakeholders in data analysis
and programming with MATLAB
• Same as the conventional mathematics
notation for matrices
• Can access a single element or multiple
elements of the matrix
• Once the indexing is right, go ahead and work

43
Indexing into Matrices

44
Accessing Single Elements
Using the (row, column) indexing
• For two dimensional arrays
A(m,n)
% m = row index, n = column index
A(2,2)
• For higher dimensional arrays specify
additional indices for page, block,etc.
A(m,n,p,...)
C3(1,2,2)
45
Accessing Single Elements
Linear indexing – column-wise indexing
• The data are stored in memory in the column-
wise fashion
– as a single column of elements
– composed of all of the columns from the matrix,
each appended to the predecessor.

46
Accessing Single Elements
Linear indexing – column-wise indexing

• A single index is used


• Indexing A(7) refers the element at A(1,3)
which is 9

47
Accessing Multiple Elements
Using the colon operator
A = magic(8) % let’s work with
% this 8-by-8 matrix
Accessing consecutive elements
• All elements in a particular row
A(4,:) % all elements in row 4
• All elements in a particular column
A(:,7) % all elements in column 7

48
Accessing Multiple Elements
A = magic(8) % still work with this matrix

Accessing certain consecutive elements


• in a particular row
A(4,3:6)
% elements in row 4, columns 3 to 6
• in a particular column
A(2:4,7)
% elements in column 7, rows 2 to 4

49
Accessing Multiple Elements
A = magic(8) % still work with this matrix
Accessing non-consecutive elements (1)
– Employ the step value in the range specification
• in a particular row
A(4,2:2:6)
% elements in row 4, columns 2,4,6
• in a particular column
A(1:3:8,7)
% elements in column 7, rows 1,4,7

50
Accessing Multiple Elements
A = magic(8) % still work with this matrix
Accessing non-consecutive elements (2)
– Employ the generic array indexing
• in a particular row
A(4,[2,3,5,8])
% elements in row 4, columns 2,3,5,8
• in a particular column
A([1,3,8],7)
% elements in column 7, rows 1,3,8
• You can control the order: e.g. A(4,[2,8,5,3])

51
Accessing Multiple Elements
Already mentioned techniques also apply to linear
indexing

All elements: A(:)


% returns a column vector of
% all elements
Accessing consecutive elements
A(14:29)
% elements accessed column-wise from
% no. 14 to no. 29

52
Accessing Multiple Elements
Already mentioned techniques also apply to linear
indexing

Accessing non-consecutive elements


A(3:5:48), A(48:-5:3)

Using generic array indexing


A([6,9,14,34]),
A([48,26,34,9])

53
Indexing into Matrices
Using the end function
• The keyword ‘end’ can be used in indexing
operations
• end returns the highest value taken on by
the subscript

A(end)% access the last element in the array

54
Indexing into Matrices
Using the end function
• Accessing multiple elements
A(4,2:end)
% access in the 4th row, elements from
% columns 2 till the last column
• Linear indexing
A(1:end/2)
% Access half of the elements
% starting from the first

55
Logical Indexing
A form of generic indexing
• Accessing multiple elements

% access in the
• Linear indexing

% Access

56
Sub-arrays
• Accessing multiple elements in a matrix
creates a sub-array (of the original )
• So far we’ve been accessing vector arrays
– Creating sub-matrices all the while

57
Your turn
• Create a 6x6 matrix of random whole
numbers
• Using the end function, access the lower right
quarter of the matrix
• Obtain a vector of 10 numbers from the 6x6
matrix indexed randomly

58
We’re Here...
 Numeric Data Types
 Integers (signed and unsigned)
 Floating-point numbers ( single and double )
 Complex numbers
 inf and NaN
 Working with Matrices (Matrices 2)
 Generating numeric and random sequences
 Concatenation of matrices
 Getting info about a matrix
 Indexing into matrices
59
Exercise 1
You are part of a team which demands you to generate unique
passwords for each of 10 applications. Each password is to be 8
characters long. Spaces and non-printing characters are not
allowed.
•Look up the ASCII character set (next slide)
•Write a simple script to generate a [10x8] array of random
characters using the rand function.
•(hint1: characters should fall in the range 33:126)
•(hint2: use the char function to convert to char array)
•Write another simple script for the same result using the
randi function.
•Which method was easier?

60
ASCII character set

• The digits at the left of the table are the left digits of the decimal
equivalents (0–127) of the character codes,
• and the digits at the top of the table are the right digits of the character
codes.
• For example, the character code for “F” is 70, and the character code for
“&” is 38.
Remember to practice

See you in the Next module...

62

You might also like