(Ebook) MATLAB Mathematics by MathWorks - The full ebook with all chapters is available for download
(Ebook) MATLAB Mathematics by MathWorks - The full ebook with all chapters is available for download
com
https://ebooknice.com/product/matlab-mathematics-49473892
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebooknice.com/product/audio-toolbox-user-s-guide-matlab-
simulink-49474718
ebooknice.com
(Ebook) Learning Matlab 6, Release 12, Matlab Student Version by The MathWorks ISBN
9780967219530, 0967219531
https://ebooknice.com/product/learning-matlab-6-release-12-matlab-student-
version-1857530
ebooknice.com
https://ebooknice.com/product/matlab-r2020a-symbolic-math-toolbox-user-s-
guide-11236344
ebooknice.com
https://ebooknice.com/product/matlab-econometrics-toolboxtm-user-s-
guide-11236174
ebooknice.com
(Ebook) MATLAB Bioinformatics Toolbox™ User's Guide by The MathWorks, Inc.
https://ebooknice.com/product/matlab-bioinformatics-toolboxtm-user-s-
guide-11236232
ebooknice.com
https://ebooknice.com/product/matlab-mapping-toolboxtm-user-s-guide-11236250
ebooknice.com
https://ebooknice.com/product/matlab-optimization-toolboxtm-user-s-
guide-11236252
ebooknice.com
(Ebook) Deep Learning Toolbox Getting Started Guide - MATLAB by The MathWorks, Inc.
https://ebooknice.com/product/deep-learning-toolbox-getting-started-guide-
matlab-43710832
ebooknice.com
(Ebook) MATLAB Computer Vision Toolbox™ User's Guide by The MathWorks, Inc.
https://ebooknice.com/product/matlab-computer-vision-toolboxtm-user-s-
guide-11236240
ebooknice.com
MATLAB®
Mathematics
R2023a
How to Contact MathWorks
Phone: 508-647-7000
Linear Algebra
2
Matrices in the MATLAB Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Creating Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Adding and Subtracting Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Vector Products and Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Multiplying Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Identity Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Matrix Inverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Kronecker Tensor Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Vector and Matrix Norms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Using Multithreaded Computation with Linear Algebra Functions . . . . . . . 2-9
Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Cholesky Factorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
LU Factorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21
QR Factorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22
Using Multithreaded Computation for Factorization . . . . . . . . . . . . . . . . 2-25
v
Powers and Exponentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26
Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Eigenvalue Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Multiple Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31
Schur Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31
Random Numbers
3
Why Do Random Numbers Repeat After Startup? . . . . . . . . . . . . . . . . . . . 3-2
vi Contents
Creating and Controlling a Random Number Stream . . . . . . . . . . . . . . . 3-19
Substreams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19
Choosing a Random Number Generator . . . . . . . . . . . . . . . . . . . . . . . . . 3-21
Configuring a Stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24
Restore State of Random Number Generator to Reproduce Output . . . . . 3-25
Sparse Matrices
4
Computational Advantages of Sparse Matrices . . . . . . . . . . . . . . . . . . . . . 4-2
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Computational Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
vii
Iterative Methods for Linear Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-56
Direct vs. Iterative Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-56
Generic Iterative Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57
Summary of Iterative Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57
Choosing an Iterative Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-59
Preconditioners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-60
Equilibration and Reordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-62
Using Linear Operators Instead of Matrices . . . . . . . . . . . . . . . . . . . . . . 4-64
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-64
Add Graph Node Names, Edge Weights, and Other Attributes . . . . . . . . 5-13
viii Contents
Polynomial Curve Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11
Computational Geometry
7
Triangulation Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
2-D and 3-D Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Triangulation Matrix Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Querying Triangulations Using the triangulation Class . . . . . . . . . . . . . . . 7-4
Interpolation
8
Gridded and Scattered Sample Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Interpolation versus Curve Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Grid Approximation Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
ix
Interpolation of Multiple 1-D Value Sets . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13
Optimization
9
Optimizing Nonlinear Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Minimizing Functions of One Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Minimizing Functions of Several Variables . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Maximizing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
fminsearch Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
x Contents
States of the Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-17
Stop Flag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-18
Function Handles
10
Parameterizing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Parameterizing Using Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Parameterizing Using Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . 10-3
xi
Solve Stiff ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23
xii Contents
Solve BVP with Singular Term . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-25
xiii
Numerical Integration
15
Integration to Find Arc Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
Fourier Transforms
16
Fourier Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
xiv Contents
Creation Functions for CompositeGate Objects . . . . . . . . . . . . . . . . . . . 17-22
xv
1
The most basic MATLAB® data structure is the matrix. A matrix is a two-dimensional, rectangular
array of data elements arranged in rows and columns. The elements can be numbers, logical values
(true or false), dates and times, strings, categorical values, or some other MATLAB data type.
Even a single number is stored as a matrix. For example, a variable containing the value 100 is stored
as a 1-by-1 matrix of type double.
A = 100;
whos A
A 1x1 8 double
If you have a specific set of data, you can arrange the elements in a matrix using square brackets. A
single row of data has spaces or commas in between the elements, and a semicolon separates the
rows. For example, create a single row of four numeric elements. The size of the resulting matrix is 1-
by-4 because it has one row and four columns. A matrix of this shape is often referred to as a row
vector.
A = [12 62 93 -8]
A = 1×4
12 62 93 -8
sz = size(A)
sz = 1×2
1 4
Now create a matrix with the same numbers, but arrange them in two rows. This matrix has two rows
and two columns.
A = 2×2
12 62
93 -8
sz = size(A)
sz = 1×2
2 2
1-2
Creating, Concatenating, and Expanding Matrices
MATLAB has many functions that help create matrices with certain values or a particular structure.
For example, the zeros and ones functions create matrices of all zeros or all ones. The first and
second arguments of these functions are the number of rows and number of columns of the matrix,
respectively.
A = zeros(3,2)
A = 3×2
0 0
0 0
0 0
B = ones(2,4)
B = 2×4
1 1 1 1
1 1 1 1
The diag function places the input elements on the diagonal of a matrix. For example, create a row
vector A containing four elements. Then, create a 4-by-4 matrix whose diagonal elements are the
elements of A.
A = [12 62 93 -8];
B = diag(A)
B = 4×4
12 0 0 0
0 62 0 0
0 0 93 0
0 0 0 -8
Concatenating Matrices
You can also use square brackets to append existing matrices. This way of creating a matrix is called
concatenation. For example, concatenate two row vectors to make an even longer row vector.
A = ones(1,4);
B = zeros(1,4);
C = [A B]
C = 1×8
1 1 1 1 0 0 0 0
D = 2×4
1-3
1 Matrices and Arrays
1 1 1 1
0 0 0 0
To concatenate several matrices, they must have compatible sizes. In other words, when you
concatenate matrices horizontally, they must have the same number of rows. When you concatenate
them vertically, they must have the same number of columns.
For example, create two matrices that both have two rows. Horizontally append the second matrix to
the first by using square brackets.
A = ones(2,3)
A = 2×3
1 1 1
1 1 1
B = zeros(2,2)
B = 2×2
0 0
0 0
C = [A B]
C = 2×5
1 1 1 0 0
1 1 1 0 0
D = horzcat(A,B)
D = 2×5
1 1 1 0 0
1 1 1 0 0
The colon is a handy way to create matrices whose elements are sequential and evenly spaced. For
example, create a row vector whose elements are the integers from 1 to 10.
A = 1:10
A = 1×10
1 2 3 4 5 6 7 8 9 10
1-4
Creating, Concatenating, and Expanding Matrices
You can use the colon operator to create a sequence of numbers within any range, incremented by
one.
A = -2.5:2.5
A = 1×6
To change the value of the sequence increment, specify the increment value in between the starting
and ending range values, separated by colons.
A = 0:2:10
A = 1×6
0 2 4 6 8 10
A = 6:-1:0
A = 1×7
6 5 4 3 2 1 0
You can also increment by noninteger values. If an increment value does not evenly partition the
specified range, MATLAB automatically ends the sequence at the last value it can reach before
exceeding the range.
A = 1:0.2:2.1
A = 1×6
Expanding a Matrix
You can add one or more elements to a matrix by placing them outside of the existing row and column
index boundaries. MATLAB automatically pads the matrix with zeros to keep it rectangular. For
example, create a 2-by-3 matrix and add an additional row and column to it by inserting an element in
the (3,4) position.
A = 2×3
10 20 30
60 70 80
A(3,4) = 1
A = 3×4
1-5
1 Matrices and Arrays
10 20 30 0
60 70 80 0
0 0 0 1
You can also expand the size by inserting a new matrix outside of the existing index ranges.
A(4:5,5:6) = [2 3; 4 5]
A = 5×6
10 20 30 0 0 0
60 70 80 0 0 0
0 0 0 1 0 0
0 0 0 0 2 3
0 0 0 0 4 5
To expand the size of a matrix repeatedly, such as within a for loop, it is a best practice to
preallocate space for the largest matrix you anticipate creating. Without preallocation, MATLAB has
to allocate memory every time the size increases, slowing down operations. For example, preallocate
a matrix that holds up to 10,000 rows and 10,000 columns by initializing its elements to zero.
A = zeros(10000,10000);
If you need to preallocate additional elements later, you can expand it by assigning outside of the
matrix index ranges or concatenate another preallocated matrix to A.
Empty Arrays
An empty array in MATLAB is an array with at least one dimension length equal to zero. Empty arrays
are useful for representing the concept of "nothing" programmatically. For example, suppose you
want to find all elements of a vector that are less than 0, but there are none. The find function
returns an empty vector of indices, indicating that it did not find any elements less than 0.
A = [1 2 3 4];
ind = find(A<0)
ind =
Many algorithms contain function calls that can return empty arrays. It is often useful to allow empty
arrays to flow through these algorithms as function arguments instead of handling them as a special
case. If you do need to customize empty array handling, you can check for them using the isempty
function.
TF = isempty(ind)
1-6
Creating, Concatenating, and Expanding Matrices
TF = logical
1
See Also
Related Examples
• “Array Indexing” on page 1-21
• “Reshaping and Rearranging Arrays” on page 1-9
• “Multidimensional Arrays” on page 1-14
• “Create String Arrays”
• “Represent Dates and Times in MATLAB”
1-7
1 Matrices and Arrays
The easiest way to remove a row or column from a matrix is to set that row or column equal to a pair
of empty square brackets []. For example, create a 4-by-4 matrix and remove the second row.
A = magic(4)
A = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
A(2,:) = []
A = 3×4
16 2 3 13
9 7 6 12
4 14 15 1
A(:,3) = []
A = 3×3
16 2 13
9 7 12
4 14 1
You can extend this approach to any array. For example, create a random 3-by-3-by-3 array and
remove all of the elements in the first matrix of the third dimension.
B = rand(3,3,3);
B(:,:,1) = [];
See Also
Related Examples
• “Reshaping and Rearranging Arrays” on page 1-9
• “Array Indexing” on page 1-21
1-8
Reshaping and Rearranging Arrays
Many functions in MATLAB® can take the elements of an existing array and put them in a different
shape or sequence. This can be helpful for preprocessing your data for subsequent computations or
analyzing the data.
Reshaping
The reshape function changes the size and shape of an array. For example, reshape a 3-by-4 matrix
to a 2-by-6 matrix.
A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
A = 3×4
1 4 7 10
2 5 8 11
3 6 9 12
B = reshape(A,2,6)
B = 2×6
1 3 5 7 9 11
2 4 6 8 10 12
As long as the number of elements in each shape are the same, you can reshape them into an array
with any number of dimensions. Using the elements from A, create a 2-by-2-by-3 multidimensional
array.
C = reshape(A,2,2,3)
C =
C(:,:,1) =
1 3
2 4
C(:,:,2) =
5 7
6 8
C(:,:,3) =
9 11
10 12
A common task in linear algebra is to work with the transpose of a matrix, which turns the rows into
columns and the columns into rows. To do this, use the transpose function or the .' operator.
1-9
1 Matrices and Arrays
A = 3×3
8 1 6
3 5 7
4 9 2
B = A.'
B = 3×3
8 3 4
1 5 9
6 7 2
A similar operator ' computes the conjugate transpose for complex matrices. This operation
computes the complex conjugate of each element and transposes it. Create a 2-by-2 complex matrix
and compute its conjugate transpose.
A = [1+i 1-i; -i i]
A = 2×2 complex
B = A'
B = 2×2 complex
flipud flips the rows of a matrix in an up-to-down direction, and fliplr flips the columns in a left-
to-right direction.
A = [1 2; 3 4]
A = 2×2
1 2
3 4
B = flipud(A)
B = 2×2
3 4
1 2
C = fliplr(A)
1-10
Reshaping and Rearranging Arrays
C = 2×2
2 1
4 3
You can shift elements of an array by a certain number of positions using the circshift function.
For example, create a 3-by-4 matrix and shift its columns to the right by 2. The second argument [0
2] tells circshift to shift the rows 0 places and shift the columns 2 places to the right.
A = [1 2 3 4; 5 6 7 8; 9 10 11 12]
A = 3×4
1 2 3 4
5 6 7 8
9 10 11 12
B = circshift(A,[0 2])
B = 3×4
3 4 1 2
7 8 5 6
11 12 9 10
To shift the rows of A up by 1 and keep the columns in place, specify the second argument as [-1 0].
C = circshift(A,[-1 0])
C = 3×4
5 6 7 8
9 10 11 12
1 2 3 4
A = [1 2; 3 4]
A = 2×2
1 2
3 4
B = rot90(A)
B = 2×2
2 4
1 3
1-11
1 Matrices and Arrays
If you rotate 3 more times by using the second argument to specify the number of rotations, you end
up with the original matrix A.
C = rot90(B,3)
C = 2×2
1 2
3 4
Sorting
Sorting the data in an array is also a valuable tool, and MATLAB offers a number of approaches. For
example, the sort function sorts the elements of each row or column of a matrix separately in
ascending or descending order. Create a matrix A and sort each column of A in ascending order.
A = magic(4)
A = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
B = sort(A)
B = 4×4
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13
Sort each row in descending order. The second argument value 2 specifies that you want to sort row-
wise.
C = sort(A,2,'descend')
C = 4×4
16 13 3 2
11 10 8 5
12 9 7 6
15 14 4 1
To sort entire rows or columns relative to each other, use the sortrows function. For example, sort
the rows of A in ascending order according to the elements in the first column. The positions of the
rows change, but the order of the elements in each row are preserved.
D = sortrows(A)
D = 4×4
4 14 15 1
1-12
Reshaping and Rearranging Arrays
5 11 10 8
9 7 6 12
16 2 3 13
See Also
Related Examples
• “Removing Rows or Columns from a Matrix” on page 1-8
• “Array Indexing” on page 1-21
1-13
1 Matrices and Arrays
Multidimensional Arrays
A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the
two dimensions are represented by rows and columns.
Each element is defined by two subscripts, the row index and the column index. Multidimensional
arrays are an extension of 2-D matrices and use additional subscripts for indexing. A 3-D array, for
example, uses three subscripts. The first two are just like a matrix, but the third dimension
represents pages or sheets of elements.
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For
example, first define a 3-by-3 matrix as the first page in a 3-D array.
A = [1 2 3; 4 5 6; 7 8 9]
A = 3×3
1 2 3
4 5 6
7 8 9
Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third
dimension. The syntax A(:,:,2) uses a colon in the first and second dimensions to include all rows
and all columns from the right-hand side of the assignment.
A(:,:,2) = [10 11 12; 13 14 15; 16 17 18]
A =
A(:,:,1) =
1-14
Multidimensional Arrays
1 2 3
4 5 6
7 8 9
A(:,:,2) =
10 11 12
13 14 15
16 17 18
The cat function can be a useful tool for building multidimensional arrays. For example, create a new
3-D array B by concatenating A with a third page. The first argument indicates which dimension to
concatenate along.
B = cat(3,A,[3 2 1; 0 9 8; 5 3 7])
B =
B(:,:,1) =
1 2 3
4 5 6
7 8 9
B(:,:,2) =
10 11 12
13 14 15
16 17 18
B(:,:,3) =
3 2 1
0 9 8
5 3 7
Another way to quickly expand a multidimensional array is by assigning a single element to an entire
page. For example, add a fourth page to B that contains all zeros.
B(:,:,4) = 0
B =
B(:,:,1) =
1 2 3
4 5 6
7 8 9
B(:,:,2) =
10 11 12
13 14 15
1-15
1 Matrices and Arrays
16 17 18
B(:,:,3) =
3 2 1
0 9 8
5 3 7
B(:,:,4) =
0 0 0
0 0 0
0 0 0
Accessing Elements
To access elements in a multidimensional array, use integer subscripts just as you would for vectors
and matrices. For example, find the 1,2,2 element of A, which is in the first row, second column, and
second page of A.
A
A =
A(:,:,1) =
1 2 3
4 5 6
7 8 9
A(:,:,2) =
10 11 12
13 14 15
16 17 18
elA = A(1,2,2)
elA = 11
Use the index vector [1 3] in the second dimension to access only the first and last columns of each
page of A.
C = A(:,[1 3],:)
C =
C(:,:,1) =
1 3
4 6
7 9
C(:,:,2) =
1-16
Multidimensional Arrays
10 12
13 15
16 18
To find the second and third rows of each page, use the colon operator to create your index vector.
D = A(2:3,:,:)
D =
D(:,:,1) =
4 5 6
7 8 9
D(:,:,2) =
13 14 15
16 17 18
Manipulating Arrays
Elements of multidimensional arrays can be moved around in many ways, similar to vectors and
matrices. reshape, permute, and squeeze are useful functions for rearranging elements. Consider
a 3-D array with two pages.
Reshaping a multidimensional array can be useful for performing certain operations or visualizing the
data. Use the reshape function to rearrange the elements of the 3-D array into a 6-by-5 matrix.
A = [1 2 3 4 5; 9 0 6 3 7; 8 1 5 0 2];
A(:,:,2) = [9 7 8 5 2; 3 5 8 5 1; 6 9 4 3 3];
B = reshape(A,[6 5])
B = 6×5
1 3 5 7 5
9 6 7 5 5
8 5 2 9 3
2 4 9 8 2
0 3 3 8 1
1 0 6 4 3
reshape operates columnwise, creating the new matrix by taking consecutive elements down each
column of A, starting with the first page then moving to the second page.
Permutations are used to rearrange the order of the dimensions of an array. Consider a 3-D array M.
1-17
1 Matrices and Arrays
M(:,:,1) = [1 2 3; 4 5 6; 7 8 9];
M(:,:,2) = [0 5 4; 2 7 6; 9 3 1]
M =
M(:,:,1) =
1 2 3
4 5 6
7 8 9
M(:,:,2) =
0 5 4
2 7 6
9 3 1
Use the permute function to interchange row and column subscripts on each page by specifying the
order of dimensions in the second argument. The original rows of M are now columns, and the
columns are now rows.
P1 = permute(M,[2 1 3])
P1 =
P1(:,:,1) =
1 4 7
2 5 8
3 6 9
P1(:,:,2) =
0 2 9
5 7 3
4 6 1
P2 =
P2(:,:,1) =
1 2 3
0 5 4
P2(:,:,2) =
4 5 6
2 7 6
P2(:,:,3) =
7 8 9
1-18
Multidimensional Arrays
9 3 1
When working with multidimensional arrays, you might encounter one that has an unnecessary
dimension of length 1. The squeeze function performs another type of manipulation that eliminates
dimensions of length 1. For example, use the repmat function to create a 2-by-3-by-1-by-4 array
whose elements are each 5, and whose third dimension has length 1.
A = repmat(5,[2 3 1 4])
A =
A(:,:,1,1) =
5 5 5
5 5 5
A(:,:,1,2) =
5 5 5
5 5 5
A(:,:,1,3) =
5 5 5
5 5 5
A(:,:,1,4) =
5 5 5
5 5 5
szA = size(A)
szA = 1×4
2 3 1 4
numdimsA = ndims(A)
numdimsA = 4
Use the squeeze function to remove the third dimension, resulting in a 3-D array.
B = squeeze(A)
B =
B(:,:,1) =
5 5 5
5 5 5
B(:,:,2) =
1-19
1 Matrices and Arrays
5 5 5
5 5 5
B(:,:,3) =
5 5 5
5 5 5
B(:,:,4) =
5 5 5
5 5 5
szB = size(B)
szB = 1×3
2 3 4
numdimsB = ndims(B)
numdimsB = 3
See Also
Related Examples
• “Creating, Concatenating, and Expanding Matrices” on page 1-2
• “Array Indexing” on page 1-21
• “Reshaping and Rearranging Arrays” on page 1-9
1-20
Array Indexing
Array Indexing
In MATLAB®, there are three primary approaches to accessing array elements based on their
location (index) in the array. These approaches are indexing by position, linear indexing, and logical
indexing.
The most common way is to explicitly specify the indices of the elements. For example, to access a
single element of a matrix, specify the row number followed by the column number of the element.
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
A = 4×4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
e = A(3,2)
e = 10
You can also reference multiple elements at a time by specifying their indices in a vector. For
example, access the first and third elements of the second row of A.
r = A(2,[1 3])
r = 1×2
5 7
To access elements in a range of rows or columns, use the colon. For example, access the elements
in the first through third row and the second through fourth column of A.
r = A(1:3,2:4)
r = 3×3
2 3 4
6 7 8
10 11 12
An alternative way to compute r is to use the keyword end to specify the second column through the
last column. This approach lets you specify the last column without knowing exactly how many
columns are in A.
r = A(1:3,2:end)
r = 3×3
1-21
1 Matrices and Arrays
2 3 4
6 7 8
10 11 12
If you want to access all of the rows or columns, use the colon operator by itself. For example, return
the entire third column of A.
r = A(:,3)
r = 4×1
3
7
11
15
In general, you can use indexing to access elements of any array in MATLAB regardless of its data
type or dimensions. For example, directly access a column of a datetime array.
t = [datetime(2018,1:5,1); datetime(2019,1:5,1)]
t = 2x5 datetime
01-Jan-2018 01-Feb-2018 01-Mar-2018 01-Apr-2018 01-May-2018
01-Jan-2019 01-Feb-2019 01-Mar-2019 01-Apr-2019 01-May-2019
march1 = t(:,3)
For higher-dimensional arrays, expand the syntax to match the array dimensions. Consider a random
3-by-3-by-3 numeric array. Access the element in the second row, third column, and first sheet of the
array.
A = rand(3,3,3);
e = A(2,3,1)
e = 0.5469
For more information on working with multidimensional arrays, see “Multidimensional Arrays” on
page 1-14.
Another method for accessing elements of an array is to use only a single index, regardless of the size
or dimensions of the array. This method is known as linear indexing. While MATLAB displays arrays
according to their defined sizes and shapes, they are actually stored in memory as a single column of
elements. A good way to visualize this concept is with a matrix. While the following array is displayed
as a 3-by-3 matrix, MATLAB stores it as a single column made up of the columns of A appended one
after the other. The stored vector contains the sequence of elements 12, 45, 33, 36, 29, 25, 91, 48,
11, and can be displayed using a single colon.
1-22
Array Indexing
A = 3×3
12 36 91
45 29 48
33 25 11
Alinear = A(:)
Alinear = 9×1
12
45
33
36
29
25
91
48
11
For example, the 3,2 element of A is 25, and you can access it using the syntax A(3,2). You can also
access this element using the syntax A(6), since 25 is sixth element of the stored vector sequence.
e = A(3,2)
e = 25
elinear = A(6)
elinear = 25
While linear indexing can be less intuitive visually, it can be powerful for performing certain
computations that are not dependent on the size or shape of the array. For example, you can easily
sum all of the elements of A without having to provide a second argument to the sum function.
s = sum(A(:))
s = 330
The sub2ind and ind2sub functions help to convert between original array indices and their linear
version. For example, compute the linear index of the 3,2 element of A.
linearidx = sub2ind(size(A),3,2)
linearidx = 6
Convert from the linear index back to its row and column form.
[row,col] = ind2sub(size(A),6)
row = 3
col = 2
Using true and false logical indicators is another useful way to index into arrays, particularly when
working with conditional statements. For example, say you want to know if the elements of a matrix A
1-23
1 Matrices and Arrays
are less than the corresponding elements of another matrix B. The less-than operator returns a
logical array whose elements are 1 when an element in A is smaller than the corresponding element
in B.
A = [1 2 6; 4 3 6]
A = 2×3
1 2 6
4 3 6
B = [0 3 7; 3 7 5]
B = 2×3
0 3 7
3 7 5
ind = A<B
0 1 1
0 1 0
Now that you know the locations of the elements meeting the condition, you can inspect the
individual values using ind as the index array. MATLAB matches the locations of the value 1 in ind to
the corresponding elements of A and B, and lists their values in a column vector.
Avals = A(ind)
Avals = 3×1
2
3
6
Bvals = B(ind)
Bvals = 3×1
3
7
7
MATLAB "is" functions also return logical arrays that indicate which elements of the input meet a
certain condition. For example, check which elements of a string vector are missing using the
ismissing function.
1-24
Array Indexing
0 0 1 0 0 1
Suppose you want to find the values of the elements that are not missing. Use the ~ operator with the
index vector ind to do this.
strvals = str(~ind)
For more examples using logical indexing, see “Find Array Elements That Meet a Condition”.
See Also
Related Examples
• “Access Data Using Categorical Arrays”
• “Access Data in Tables”
• “Structure Arrays”
• “Access Data in Cell Array”
External Websites
• Programming: Organizing Data (MathWorks Teaching Resources)
1-25
2
Linear Algebra
The MATLAB environment uses the term matrix to indicate a variable containing real or complex
numbers arranged in a two-dimensional grid. An array is, more generally, a vector, matrix, or higher
dimensional grid of numbers. All arrays in MATLAB are rectangular, in the sense that the component
vectors along any dimension are all the same length. The mathematical operations defined on
matrices are the subject of linear algebra.
Creating Matrices
MATLAB has many functions that create different kinds of matrices. For example, you can create a
symmetric matrix with entries based on Pascal's triangle:
A = pascal(3)
A =
1 1 1
1 2 3
1 3 6
Or, you can create an unsymmetric magic square matrix, which has equal row and column sums:
B = magic(3)
B =
8 1 6
3 5 7
4 9 2
Another example is a 3-by-2 rectangular matrix of random integers. In this case the first input to
randi describes the range of possible values for the integers, and the second two inputs describe the
number of rows and columns.
C = randi(10,3,2)
C =
9 10
10 7
2 1
A column vector is an m-by-1 matrix, a row vector is a 1-by-n matrix, and a scalar is a 1-by-1 matrix.
To define a matrix manually, use square brackets [ ] to denote the beginning and end of the array.
Within the brackets, use a semicolon ; to denote the end of a row. In the case of a scalar (1-by-1
matrix), the brackets are not required. For example, these statements produce a column vector, a row
vector, and a scalar:
u = [3; 1; 4]
v = [2 0 -1]
s = 7
2-2
Matrices in the MATLAB Environment
u =
3
1
4
v =
2 0 -1
s =
7
For more information about creating and working with matrices, see “Creating, Concatenating, and
Expanding Matrices” on page 1-2.
X = A + B
X =
9 2 7
4 7 10
5 12 8
Y = X - A
Y =
8 1 6
3 5 7
4 9 2
Addition and subtraction require both matrices to have compatible dimensions. If the dimensions are
incompatible, an error results:
X = A + C
Error using +
Matrix dimensions must agree.
u = [3; 1; 4];
v = [2 0 -1];
x = v*u
x =
X = u*v
2-3
Random documents with unrelated
content Scribd suggests to you:
MIRACLES IN FRUITS.
All know that after the sap begins to flow in the spring, a vine, if
cut, will bleed. It seems that at this early period of its development
the sap vessels have no power of contraction. Many suppose that
the same state of things continues throughout the growing season,
and are afraid to cut their vines. But after the vine has begun to
grow freely (when the leaves, for example, are as large as the palm
of one’s hand), a wound very soon contracts, bleeds little or none,
and heals over as in a tree. Any pruning which is necessary upon the
old wound may, therefore, be fearlessly performed.
Some inexpert cultivators, in order to let the sun fall upon the
grapes, pluck off the leaves; hoping thus to procure sweeter grapes.
This is the very way to have acid fruit. Where is the sugar prepared
for the cluster but in these very leaves which are taken off? Without
leaves, the sap which flows into the cluster has undergone but
imperfectly those chemical changes on which the fruit depends.
Every leaf in the neighborhood of the fruit is precious.
MILDEW ON GRAPES.
Many permit the fruit of the vines to perish before their eyes from
the ravages of mildew, ignorant that an effectual remedy is within
their reach. It is simply to dust the branches with flowers of sulphur.
It is best done while the dew is on.
When vines are trained upon the sides of a house or fence, it is well
to whitewash the surfaces on which they are fastened with a wash in
which flowers of sulphur has been largely mixed.
It is recommended by some cultivators to employ such a whitewash
for the wood of the vine, covering all the main stems with it; but all
these methods result in the one thing—the application of sulphur as
a remedy for mildew.
HOW TO OBTAIN GRAPE VINES.
We do not think the pear does so well in any other way as on its own
root. But it has been found extremely difficult to obtain the requisite
stock. Pear-seeds are scarce. When obtained, the seedlings have
proved intractable, and left the nurseryman oftentimes in the lurch.
The first and best substitute for pear-stock, is the root of the pear—
great quantities may be obtained when removing pear-trees in the
autumn from the nursery, and also without any injury to the trees,
roots may be taken from old bearing-trees. These are to be grafted
in the manner already described in our pages. Next to this, the
quince stock is to be chosen. The pear is dwarfed upon it. In other
words, the two are but imperfectly suited to each other, and the
scion does not develop according to its original nature. But this very
dwarfing adds something to the good qualities of the fruit, affords
trees so small that, at eight feet apart, they make beautiful linings to
a walk or border, and, morever, brings the pear to its fruit several
years earlier than if it were on its own bottom. But on the other
hand, the pear on quince is comparatively short-lived. The white-
thorn has been tried as a stock and not without success, but it is
hardly to be used except in extremities.
Last, and worst of all, comes the apple. The scion grows as
vigorously upon the apple as upon a stock of its own species, and
we do not know that the fruit deteriorates. But the trees seem to
have no constitution. After a few bearings they seem struck with
irremediable weakness, and soon run down and die. Nurserymen
ought not, therefore, to graft the pear upon the apple. To do so, if
advised of the foregoing facts, cannot be honest. Our attention has
been called to the subject by some painful experience of our own.
Neshanoc Potato.—This potato (pronounced Meshanoc), was raised
from the seed about the year 1800, by John Gilkey, Mercer county,
Pennsylvania. He called it Neshanoc, from a creek near to which he
lived. It was called by some, Mercer, from the county in which it was
raised. It is extensively cultivated, and deserves to be. Mr. Gilkey
was an Irishman—of course a judge of good potatoes.
SEEDLINGS FROM BUDDED PEACHES.
Mr. Nicholas Longworth inquires: “Will the pit of the budded peach
produce the same fruit as the bud, or as the stock, or a mixture of
the two?” And he also says, “I have never fairly tested the question,
but my experience led me to believe that the budded pit produced
the same fruit as the original stock.”
So far as this question can be determined (independently of
experiment) upon the known laws of the vegetable kingdom, we say
that it will not produce fruit like that of the original stock; nor will it,
on the other hand, with any certainty, reproduce the budded kind.
If the pit of a budded variety takes after the stock, we must very
much change our theory of the office of leaves, and perhaps of the
bark. At present, the received and orthodox teaching is, that the sap
from the root is crude and undigested until it has received in the leaf
a chemical change. Until then, the sap does not materially influence
the vegetable tissue, nor form new substance, or affect the fruit. But
after its elaboration in the leaf, a returning current of prepared sap
(similar in its functions to arterial blood), sets downward, distributing
to every part of the vegetable economy the properties required by
each. The sap arising from the root, does not touch the channel of
fruit until it has been chemically changed; and the difference
exhibited in the fruit of one tree compared with another, arises,
primarily from the nature of the sap which it receives; the sap
receives its qualities by a digestion in the leaf.[15] In all cases, then,
we suppose the leaf to determine the nature of the fruit (and the
root in no case, and the trunk in no case), since the stem is, so far
as sap is concerned, but a bundle of canals for its passage—a mere
highway for transmission—and not like the leaf, a laboratory for its
preparation![16]
We may be reminded that a stock, in point of fact, does influence
the fruit. It is indisputable that pears are changed on quince roots.
The Wilkinson, grafted upon the quince, is smaller, more prolific,
higher flavored, and of a brighter red cheek than if grafted on the
pear. The Duchesse d’Angoulême is larger and better on the quince
than on its own roots. But what is the influence in this case? When a
free-grower is put upon a slow-grower, the point of junction
becomes a point of comparative obstruction to the return-sap. It is
only a wholesome process of ringing, or decortication. Lindley says:
“When pears are worked upon the wild species, apples upon crabs,
and peaches upon peaches, the scion is, in regard to fertility, exactly
in the same state as if it had not been grafted at all: while, on the
other hand, a great increase of fertility, is the result of grafting pears
upon quinces, peaches upon plums, apples upon the thorn, and the
like. In these cases, the food absorbed from the earth by the root of
the stock is communicated slowly.” And Manning adds: “No other
influence have we ever noticed exercised by the scion upon the
stock.”
But if, after all, it can be shown by actual trial, that the pits of
budded peaches DO go back to the fruit of the stock, why we must
receive it, in spite of all theory; for, (and some would do well to heed
the maxim), facts must rule our theories, and not theories our fact.
But we may properly put any facts seeming to contravene the
received theory of the functions of plants in producing fruit, upon
their oath, and refuse them, unless they are unquestionable and
relevant.
Suppose a budded peach not to yield a fruit at all like the bud,
suppose it to resemble the fruit of the stock, it does not follow that
the stock influenced the fruit to such a change. Mr. Longworth
knows how freely some peaches “sport,” and that all peaches may
be made to do it. If a Melacatune be budded upon a Red Rareripe,
and the Melacatune pit shows a fruit resembling the Red Rareripe, it
must be shown that the blossom had not been crossed by the busy
offices of flies, bees, etc., with the pollen of contiguous Red
Rareripe-trees.
When a tree is even solitary, it does not follow that a change in fruit
which shall make it resemble the stock more than the graft, results
from the force of the stock on the grafted fruit, for seedlings of
grafted fruit are, notoriously often, base and degenerate; and the
resemblance might be accidental, for seedlings of different origin are
often strikingly alike.
While we are aware of no facts which justify Mr. Longworth’s
suspicion, that the pits of budded varieties produce kinds like the
stock on which the bud was put, we have facts enough showing that
“budded pits” produce their own kind.
It may be added that thoroughly ripe peaches are less inclined to
“sport” than those which are partially green.
[15]The fruit itself still further elaborates the sap, else a peach would be
as acrid as the juice of the peach leaf.
[16]Loudon (Encyclopædia of Gardening, p. 448), has the following
remarks:
“The bark is the medium in which the proper juices of the plant, in their
descent from the leaves, are finally elaborated and brought to the state
which is peculiar to the species. From the bark these juices are
communicated to the medullary rays, to be by them deposited in the
tissue of the wood. The character of timber, therefore, depends chiefly
upon the influence of the bark: and hence, it is that the wood formed
above a graft never partakes, in the slightest degree, of the nature of the
wood below it. The bark, when young and green, like the leaves, is
supposed, like them, to elaborate the sap, and hence may be considered
as the universal leaf of a plant.”
These views corroborate the reasoning above, although Loudon extends
the functions of the leaf to the bark. We have not been able, in our limited
range of books, to find any other authority for this statement, respecting
the “young and green bark.”
CARE OF PEACH-TREES.
Take a light hoe and remove the earth from the trunk of your trees.
If there are worms there you may detect them from the gum which
has exuded, or by the channels which they have made in the bark,
or if by neither of these, by the discoloration of the bark in spots.
Scrape the bark gently with the back of a knife, and you can easily
detect the traces of worms if any are there. Cut freely and boldly
both ways along their track so as to lay bare the channel in its whole
length—remove the worm, and the bark will very soon heal.
Sometimes four, six, and even more will be found in one tree. The
ashes of stone coal, blacksmiths’ cinders, wood ashes, lime, the
refuse stems of tobacco, planting tansy around the trunk, these, and
dozens of other remedies are proposed. For our own part we rely
solely on our jack-knife. In March or April, and then again in August
or September, according to the season, we search the trunk
thoroughly. We can attend to twenty trees in an hour or two; and
when eating freely of delicious peaches we never had a qualm of
regret for having so spent the time.
We have practised sowing salt under fruit-trees with decided
advantage. If one pound of saltpetre be added to every six pounds
of salt, it will be yet better. We sow enough to make the ground look
moderately white, and prefer to do it in wet weather.
The most salable butter, quality being equal, is that which is neatest
done up. There is a great deal in the looks of a thing. You’ll always
find it so.
RENOVATING PEACH-TREES.
Every farmer who expects his wife to make good butter, after
furnishing her with some good, well-fed milk cows, should provide
her with good milk-pans—large and shallow, so as to present a large
surface for the cream to rise on, and enough of them to hold all her
milk, and allow it to remain undisturbed long enough for all the
cream to rise. These pans should be nicely washed every time the
milk is emptied out of them, and always be clear and bright when
filled.
AN APOLOGUE OR APPLE-LOGUE.
Two men planted out each one hundred apple-trees. In six or seven
years they began to bear. One had spared no pains to bring his
orchard into the highest condition. He had constantly cultivated the
soil about them, scraped off the rough bark, washed them with
urinated soap, picked off every worm and nursed them as if they
had been children. The other, pursuing a cheaper plan, simply let his
trees alone; but the moss, and canker-worms took his place and
attended to them every year. When the orchards began to bear, the
careful man had the best fruit, and the careless man covered his
folly by cursing the nursery-man for selling him poor trees. In a year
or two the careful man had two bushels to the other’s one from each
tree. Not to be outdone, the latter determined to have as many
apples as the former, and set out another hundred trees. By and by,
when they bore, the other orchard had so improved that it produced
twice as many yet; another hundred trees were therefore planted. In
process of time the first orchard of one hundred trees still sent more
fruit to market than the three hundred trees of the careless man,
who now gave up and declared that he never did have luck, and it
was of no use to try on his soil to raise good fruit.
1. When a man is too shiftless to take good care of two horses, he
buys two more, and gets from the four what he might get from two.
2. A farmer who picks up a cow simply because it is not an ox, and
is, nominally, lactiferous, and then lets the creature work for a living,
very soon buys a second, and a third, and a fourth, and gets from
them all, what he should have had from one good one.
3. A farmer had one hundred acres. Instead of getting seventy-five
bushels of corn to the acre, he gets forty and makes it up by
cultivating twice as many acres; instead of thirty bushes of wheat he
gets twelve, and puts in acres enough to make up; instead of
making one hundred acres do the work of three hundred, he buys
more land, and allows three hundred to do only the work of one
hundred.
4. A young woman, with a little pains, can have three times as many
clothes as she needs, and then not look so well as a humble
neighbor who has not half her wardrobe; wherefore, we close with
some proverbs made for the occasion:
Active little is better than lazy much.
Carefulness is richer than abundance.
Large farming is not always good farming, and small farming is often
the largest.
SELECT LIST OF APPLES.
SUMMER APPLES.
AUTUMN APPLES.
WINTER APPLES.
15. Gloria Mundi or Monstrous Pippin. Tree, one of the most upright,
top close, and resembling the pear. Wood medium sized, healthy,
vigorous growth, wood ripens early, not subject to frost-blight; bears
on moderately young trees. It works well from the bud, and also
extremely well grafted on roots, and grows straight and finely for
nursery purposes. Fruit very large, green, changes when dead-ripe
to a yellowish white. Flavor mild, subacid; flesh melting and spicy.
Ripens in November, at the same time with the Golden Russet, but
will not keep as long. A native.
16. Black Apple.—Tree low, spreading, and round topped; wood of
medium vigor, healthy, ripens early, and not subject to frost-blight.
Grafts on the root kindly; not so favorable for budding as the No. 15;
bears remarkably young, and abundantly to a fault. Fruit medium
sized; color very dark red, almost black, with grey rusty spots about
the stem; flesh tender, breaking; moderately juicy, flavor rather
sweet, though not a real sweet apple. No apple would stand fairer as
an early winter fruit, were it not for a peculiar, dry, raw taste,
somewhat resembling the taste of uncooked corn meal. Ripens from
November to January. It is a native.
17. Newton Spitzenburg.—Tree, not large, upright but not compact,
top open; wood of medium size and vigor of growth; healthy, ripens
early, and yet, now and then, it takes the frost-blight; bears
moderately young, every other year, very abundantly; grafts well on
the root, buds only moderately well, good for nursery handling.
Fruit, varying much in size, but often large, flesh melting, juicy;
flavor rich, spicy, subacid; ripens from November to January.
18. Rhode Island Greening.—Tree large, very spreading and drooping,
grows vigorously, healthy, ripens early, not subject to frost-blight;
bud takes well; but, whether grafted on the root, or budded, it will
plague the nurseryman by its disposition to spread and twist about
like a quince bush. It should be budded on strong stocks at the
height at which the top is to be formed; but it always overgrows the
stock. Fruit very large, color green, with cloudy spots dotted with
pin-point black specks; flesh breaking, tender and juicy: flavor mild,
rich, subacid; a very popular fruit. Ripens from November to
January.
19. Hubbardston Nonesuch.—Admirable in nursery; works well on root
or by bud. We give Downing’s description, as it has not fruited in this
region.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com