4. Операции над массивами
Функции dot, cross, norm и др.
Сортировка массива
Проверка упорядоченности
Issorted
Determine whether set elements are in sorted order
TF = issorted(A) returns logical 1 (true) if the elements of A are in sorted order, and logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is considered to be sorted if A and the output of sort(A) are equal.
TF = issorted(A, 'rows') returns logical 1 (true) if the rows of two-dimensional matrix A are in sorted order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output of sortrows(A) are equal.
Note Only the issorted(A) syntax supports A as a cell array of strings.
For character arrays, issorted uses ASCII, rather than alphabetical, order.
You cannot use issorted on arrays of greater than two dimensions.
Example 1 — Using issorted on a vector
A = [5 12 33 39 78 90 95 107 128 131];
issorted(A)
ans = 1
Example 2 — Using issorted on a matrix
A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
issorted(A, 'rows')
ans = 0
B = sortrows(A)
B =
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
17 24 1 8 15
23 5 7 14 16
issorted(B)
ans = 1
Сортировка столбцов
Sortrows
B = sortrows(A) sorts the rows of A in ascending order. Argument A must be either a matrix or a column vector. For strings, this is the familiar dictionary sort. When A is complex, the elements are sorted by magnitude, and, where magnitudes are equal, further sorted by phase angle on the interval .
B = sortrows(A,column) sorts the matrix based on the columns specified in the vector column. If an element of column is positive, the MATLAB® software sorts the corresponding column of matrix A in ascending order; if an element of column is negative, MATLAB sorts the corresponding column in descending order. For example, sortrows(A,[2 -3]) sorts the rows of A first in ascending order for the second column, and then by descending order for the third column.
[B,index] = sortrows(A,...) also returns an index vector index.
If A is a column vector, then B = A(index). If A is an m-by-n matrix, then B = A(index,:).
Start with a mostly random matrix, A:
rand('state',0)
A = floor(rand(6,7) * 100);
A(1:4,1)=95; A(5:6,1)=76; A(2:4,2)=7; A(3,3)=73
A =
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
76 61 93 81 27 46 83
76 79 91 0 19 41 1
When called with only a single input argument, sortrows bases the sort on the first column of the matrix. For any rows that have equal elements in a particular column, (e.g., A(1:4,1) for this matrix), sorting is based on the column immediately to the right, (A(1:4,2) in this case):
sortrows(A)
ans =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 7 40 35 60 93 67
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 45 92 41 13 1 84
When called with two input arguments, sortrows bases the sort entirely on the column specified in the second argument. Rows that have equal elements in this column are sorted; rows with equal elements in other columns are left in their original order:
sortrows(A,1)
ans =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
This example specifies two columns to sort by: columns 1 and 7. This tells sortrows to sort by column 1 first, and then for any rows with equal values in column 1, to sort by column 7:
sortrows(A,[1 7])
ans =
76 79 91 0 19 41 1
76 61 93 81 27 46 83
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 7 40 35 60 93 67
95 45 92 41 13 1 84
Sort the matrix using the values in column 4 this time and in reverse order:
sortrows(A, -4)
ans =
95 7 73 89 20 74 52
76 61 93 81 27 46 83
95 45 92 41 13 1 84
95 7 40 35 60 93 67
95 7 73 5 19 44 20
76 79 91 0 19 41 1
Сортировка в возрастающем порядке
>> C=[9 3 0 16 2 7 5 10]; [c,n]=sort(C)
c = 0 2 3 5 7 9 10 16
n = 3 5 2 7 6 1 8 4
в убывающем порядке
>> cc=sort(C,'descend')
cc = 16 10 9 7 5 3 2 0
Вызов sort с двумя выходными аргументами приводит к образованию массива индексов соответствия элементов упорядоченного и исходного массивов
Тренировка
>> A=[1 2 3 4 5 6]; var(A) ans = 3.5000
>> mean(A) ans = 3.5000
>> median(A) ans = 3.5000
>> dot(A,A) ans = 91
>> A*A' ans = 91
>> norm(A) ans = 9.5394
>> ans*ans ans = 91
>> cross(A,A) ??? Error using ==> cross A and B must have at least one dimension of length 3.
>> B=[1 2 3]; cross(B,B) ans = 0 0 0
>> C=[4 5 6]; cross(B,C) ans = -3 6 -3
>> prod(A) ans = 720
cumprod(1:5) ans = 1 2 6 24 120
f = factor(123) f = 3 41
B = sqrt(X) returns the square root of each element of the array X. For the elements of X that are negative or complex, sqrt(X) produces complex results.
Переворачивание х (flip) слева направо (from left to right)
>> x = [1 2 3 4 5]; a=fliplr(x)
a = 5 4 3 2 1
Сопряжение и транспозиция
>> f=5-2j
f = 5.0000 - 2.0000i
>> f'
ans =5.0000 + 2.0000i
>> A=[1 2 3 4; 5 6 7 8];
>> A'= 1 5
2 6
3 7
4 8
Определитель квадратной матрицы
>> B=[1 2 3; 4 5 6; 7 8 9]; d=det(B) =0
>> B=[1 2; 3 4]; d=det(B) = -2
Обратная матрица
>> B^-1 =
-2.0000 1.0000
1.5000 -0.5000
(то же – с помощью функции inv)
Обратное (левое) деление. Решение систем линейных уравнений
>> A=[2 3 -1; 3 4 -3; 2 0 5]; B=[3; 1; 8];
>> X=A\B X = -0.3333
1.8000
1.7333
diff
Differences and approximate derivatives
Syntax
Y = diff(X)
Y = diff(X,n)
Y = diff(X,n,dim)
Description
Y = diff(X) calculates differences between adjacent elements of X.
If X is a vector, then diff(X) returns a vector, one element shorter than X, of differences between adjacent elements:
[X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]
If X is a matrix, then diff(X) returns a matrix of row differences:
[X(2:m,:)-X(1:m-1,:)]
In general, diff(X) returns the differences calculated along the first non-singleton (size(X,dim) > 1) dimension of X.
Y = diff(X,n) applies diff recursively n times, resulting in the nth difference. Thus, diff(X,2) is the same as diff(diff(X)).
Y = diff(X,n,dim) is the nth difference function calculated along the dimension specified by scalar dim. If order n equals or exceeds the length of dimension dim, diff returns an empty array.
Remarks
Since each iteration of diff reduces the length of X along dimension dim, it is possible to specify an order n sufficiently high to reduce dim to a singleton (size(X,dim) = 1) dimension. When this happens, diff continues calculating along the next nonsingleton dimension.
Examples
The quantity diff(y)./diff(x) is an approximate derivative.
x = [1 2 3 4 5];
y = diff(x)
y = 1 1 1 1
z = diff(x,2)
z = 0 0 0
Given, A = rand(1,3,2,4);
diff(A) is the first-order difference along dimension 2.
diff(A,3,4) is the third-order difference along dimension 4.
Еще есть функции:
hess Hessenberg form of matrix
schur Schur decomposition
qz QZ factorization for generalized eigenvalues
triu Upper triangular part of matrix
tril Lower triangular part of matrix
spdiags Extract and create sparse band and diagonal matrices
full Convert sparse matrix to full matrix
bsxfun Apply element-by-element binary operation to two arrays with singleton expansion enabled
arrayfun Apply function to each element of array
spfun Apply function to nonzero sparse matrix elements
spy Visualize sparsity pattern
gplot Plot nodes and links representing adjacency matrix (матрицу смежности ) - построение графа
qr Orthogonal-triangular decomposition
null Null space
orth Range space of matrix
symamd Symmetric approximate minimum degree permutation
chol Cholesky factorization
sprand Sparse uniformly distributed random matrix
nnz Number of nonzero matrix elements
и др.
