Как найти ранг матрицы в матлабе

Main Content

Syntax

Description

example

k = rank(A) returns the rank of
matrix A.

Use sprank to determine the
structural rank of a sparse matrix.

example

k = rank(A,tol)
specifies a different tolerance to use in the rank computation. The rank is computed
as the number of singular values of A that are larger than
tol.

Examples

collapse all

Rank of Matrix

Determine whether a matrix is full rank.

Create a 3-by-3 matrix. The values in the third column are twice as large as those in the second column.

A = [3 2 4; -1 1 2; 9 5 10]
A = 3×3

     3     2     4
    -1     1     2
     9     5    10

Calculate the rank of the matrix. If the matrix is full rank, then the rank is equal to the number of columns, size(A,2).

Since the columns are linearly dependent, the matrix is rank deficient.

Specify Rank Tolerance

Calculate the rank of a matrix using a tolerance.

Create a 4-by-4 diagonal matrix. The diagonal has one small value equal to 1e-15.

A = [10 0 0 0; 0 25 0 0; 0 0 34 0; 0 0 0 1e-15]
A = 4×4

   10.0000         0         0         0
         0   25.0000         0         0
         0         0   34.0000         0
         0         0         0    0.0000

Calculate the rank of the matrix.

The matrix is not considered to be full rank, since the default algorithm calculates the number of singular values larger than max(size(A))*eps(norm(A)). For this matrix, the small value on the diagonal is excluded since it is smaller than the tolerance.

Calculate the rank of the matrix again, but specify a tolerance of 1e-16.

Input Arguments

collapse all

AInput matrix
matrix

Input matrix.

Data Types: single | double
Complex Number Support: Yes

tolTolerance
max(size(A))*eps(norm(A)) | scalar

Tolerance, specified as a scalar. See the Algorithms
section for more information.

Example: rank(A,1e-5)

More About

collapse all

Rank

The number of linearly independent columns in a matrix is the
rank of the matrix. The row and column rank of a matrix are
always equal.

A matrix is full rank if its rank is the highest possible for
a matrix of the same size, and rank deficient if it does not
have full rank. The rank gives a measure of the dimension of the
range or column space of the matrix,
which is the collection of all linear combinations of the columns.

Algorithms

rank uses a method based on the singular value decomposition, or
SVD. The SVD algorithm is more time consuming than some alternatives, but it is also the
most reliable.

The rank of a matrix A is computed as the number of singular values
that are larger than a tolerance. By default, the tolerance is
max(size(A))*eps(norm(A)). However, you can specify a different
tolerance with the command rank(A,tol).

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

  • Code generation does not support sparse matrix inputs for this
    function.

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Usage notes and limitations:

  • Code generation does not support
    sparse matrix inputs for this function.

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For
more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

This function fully supports distributed arrays. For more
information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

Version History

Introduced before R2006a

  • Trial Software
  • Trial Software
  • Product Updates
  • Product Updates

rank

Синтаксис

Описание

пример

k = rank(A) возвращает ранг матричного A.

Использование sprank определить структурный ранг разреженной матрицы.

пример

k = rank(A,tol) задает различный допуск, чтобы использовать в расчете ранга. Ранг вычисляется как число сингулярных значений A это больше, чем tol.

Примеры

свернуть все

Ранг матрицы

Определите, является ли матрица полным рангом.

Создайте 3х3 матрицу. Значения в третьем столбце являются вдвое более большими, чем те во втором столбце.

A = [3 2 4; -1 1 2; 9 5 10]
A = 3×3

     3     2     4
    -1     1     2
     9     5    10

Вычислите ранг матрицы. Если матрица является полным рангом, то ранг равен количеству столбцов, size(A,2).

Поскольку столбцы линейно зависимы, матрица имеет неполный ранг.

Задайте допуск ранга

Вычислите ранг матрицы с помощью допуска.

Создайте диагональную матрицу 4 на 4. Диагональ имеет одно маленькое значение, равное 1e-15.

A = [10 0 0 0; 0 25 0 0; 0 0 34 0; 0 0 0 1e-15]
A = 4×4

   10.0000         0         0         0
         0   25.0000         0         0
         0         0   34.0000         0
         0         0         0    0.0000

Вычислите ранг матрицы.

Матрица не считается полным рангом, поскольку алгоритм по умолчанию вычисляет число сингулярных значений, больше, чем max(size(A))*eps(norm(A)). Для этой матрицы исключено маленькое значение на диагонали, поскольку это меньше, чем допуск.

Вычислите ранг матрицы снова, но задайте допуск 1e-16.

Входные параметры

свернуть все

AВведите матрицу
матрица

Введите матрицу.

Типы данных: single | double
Поддержка комплексного числа: Да

tol Допуск
max(size(A))*eps(norm(A)) | скаляр

Допуск в виде скаляра. Смотрите раздел Algorithms для получения дополнительной информации.

Пример: rank(A,1e-5)

Больше о

свернуть все

Ранг

Количество линейно независимых столбцов в матрице является рангом матрицы. Ранг строки и столбца матрицы всегда равен.

Матрица A является полным рангом, если его ранг является максимально возможным для матрицы, одного размера, и неполный ранг, если это не имеет полного ранга. Ранг дает меру размерности области значений или пробела столбца матрицы, которая является набором всех линейных комбинаций столбцов.

Алгоритмы

rank использует метод на основе сингулярного разложения или SVD. Алгоритм SVD является более трудоемким, чем некоторые альтернативы, но это является также самым надежным.

Ранг матричного A вычисляется как число сингулярных значений, которые больше, чем допуск. По умолчанию допуском является max(size(A))*eps(norm(A)). Однако можно задать различный допуск с командой rank(A,tol).

Расширенные возможности

Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.

Указания и ограничения по применению:

  • Генерация кода не поддерживает входные параметры разреженной матрицы для этой функции.

Генерация кода графического процессора
Сгенерируйте код CUDA® для NVIDIA® графические процессоры с помощью GPU Coder™.

Указания и ограничения по применению:

  • Генерация кода не поддерживает входные параметры разреженной матрицы для этой функции.

Основанная на потоке среда
Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool.

Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.

Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.

Эта функция полностью поддерживает массивы графического процессора. Для получения дополнительной информации смотрите функции MATLAB Запуска на графическом процессоре (Parallel Computing Toolbox).

Представлено до R2006a

Main Content

Find rank of symbolic matrix

Syntax

Description

example

rank(A) returns the
rank of symbolic matrix A.

Examples

Find Rank of Matrix

syms a b c d
A = [a b; c d];
rank(A)

Rank of Symbolic Matrices Is Exact

Symbolic calculations return the exact rank
of a matrix while numeric calculations can suffer from round-off errors.
This exact calculation is useful for ill-conditioned matrices, such
as the Hilbert matrix. The rank of a Hilbert matrix of order n is n.

Find the rank of the Hilbert matrix of order 15 numerically.
Then convert the numeric matrix to a symbolic matrix using sym and
find the rank symbolically.

H = hilb(15);
rank(H)
rank(sym(H))

The symbolic calculation returns the correct rank of 15.
The numeric calculation returns an incorrect rank of 12 due
to round-off errors.

Rank Function Does Not Simplify Symbolic Calculations

Consider this matrix

After simplification of 1-sin(x)^2 to cos(x)^2,
the matrix has a rank of 1. However, rank returns
an incorrect rank of 2 because it does not take
into account identities satisfied by special functions occurring in
the matrix elements. Demonstrate the incorrect result.

syms x
A = [1-sin(x) cos(x); cos(x) 1+sin(x)];
rank(A)

rank returns an incorrect result because
the outputs of intermediate steps are not simplified. While there
is no fail-safe workaround, you can simplify symbolic expressions
by using numeric substitution and evaluating the substitution using vpa.

Find the correct rank by substituting x with
a number and evaluating the result using vpa.

However, even after numeric substitution, rank can
return incorrect results due to round-off errors.

Input Arguments

collapse all

AInput
number | vector | matrix | symbolic number | symbolic vector | symbolic matrix

Input, specified as a number, vector, or matrix or a symbolic
number, vector, or matrix.

Version History

Introduced before R2006a

·       
Length
(
V)
определяет
длину вектора
V;

·       
Prod
(
V)
или
prod
(
A,
K)
– вычисляет произведение элементов массива
V или произведения столбцов или
строк матрицы в зависимости от значения
k;

·       
Sum
(
V)
или
sum
(
A,
k)

вычисляет сумму элементов массива
V или сумму столбцов или строк
матрицы в зависимости от значения
k;

·       
Dot
(
v1,
v2)

вычисляет скалярное произведение векторов
v1 и v2, то же значение выдаст функция sum (v1.*v2);

·       
Cross
(
v1,
v2)
– определяет векторное произведение векторов
v1 и v2;

·       
Min
(
V)
находит
минимальный элемент массива
V,
вызов  в формате [
k, n]=min (V) дает возможность определить
минимальный элемент
k
и его номер в массиве
n;

·       
Max
(
V)
находит
максимальный элемент массива
V или при [k, n]=max (V) определяет максимум и его номер;

·       
Sort
(
V)
– выполняет упорядочивание массива
V;

·       
Det
(М)
  — вычисляет опеределитель квадратной матрицы
М;

·       
Rank
(
M)

определяет ранг матрицы М;

·       
Norm
(
M,
p)
возвращает
различные виды норм матрицы
M в зависимости от  p
(
p=1,
2
inf,
fro);

·       
Cond
(
M,
p)
возвращает
число обусловленности матрицы
M,
основанное на норме 
p;

·       
Eye
(
n,
m)
или
eye
(
n)

возвращает прямоугольную матрицу с единицами по главной диагонали или
квадратную единичную матрицу;

·       
Ones
(
n,
m)
или ones (n) – формирует
прямоугольную или квадратную матрицу, состоящую из единиц;

·       
Zeros
(
n,
m)
или
zeros
(
n)
– возвращает прямоугольную или квадратную нулевую матрицу;

·       
 Diag (V, n) или diag (V) – возвращает
квадратную матрицу с элементами
V
на
k
диагонали или элементами
V
на главной диагонали;

·       
Cat
(
n,
A,
B)
или
cat
(
n,
A,
B,
C,
…) –
объединяет матрицы A и B или все входящие матрицы;

·       
Inv
(
M)

возвращает матрицу, обратную к М;

·       
Eig
(
M)
– возвращает вектор собственных значений матрицы М, вызов функции в формате [
V, D]=eig (M) даст матрицу V, столбцы которой – собственные
векторы матрицы
M,
и диагональную матрицу
D,
содержащую собственные значения матрицы
M;

·       
Linsolve
(
A,
b)

возвращает решение системы линейных уравнений
A*x=b, вызов в формате  linsolve (A, b, options) позволяет задать
метод решения уравнения. Если задать функцию в виде [
x, r]= linsolve (A, b), то она вернет x – решение системы и r – ранг матрицы A.

·       
Rref
(
M)

осуществляет приведение матрицы М к треугольной форме, используя метод
исключений Гаусса;

·       
Chol
(
M)
возвращает
разложение по Халецкому для положительно определенной симметрической матрицы М;

·       
Lu
(
M)
выполняет
LU-разложение,
возвращает две матрицы: нижнюю треугольную
L  и верхнюю треугольную U;

·       
Gr
(
M)

выполняет
QR
– разложение, возвращает ортогональную матрицу
Q и верхнюю треугольную R;

rank

Rank of a matrix

Syntax

  • k = rank(A)
    k = rank(A,tol)
    

Description

The rank function provides an estimate of the number of linearly independent rows or columns of a full matrix.

k = rank(A)
returns the number of singular values of A that are larger than the default tolerance, max(size(A))*norm(A)*eps.

k = rank(A,tol)
returns the number of singular values of A that are larger than tol.

Remark

Use sprank to determine the structural rank of a sparse matrix.

Algorithm

There are a number of ways to compute the rank of a matrix. MATLAB uses the method based on the singular value decomposition, or SVD. The SVD algorithm is the most time consuming, but also the most reliable.

The rank algorithm is

  • s = svd(A);
    tol = max(size(A))*s(1)*eps;
    r = sum(s > tol);
    

See Also

sprank

References

[1]  Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide (http://www.netlib.org/lapack/lug/
lapack_lug.html), Third Edition, SIAM, Philadelphia, 1999.

   randperm   rat, rats 

Понравилась статья? Поделить с друзьями:
  • Как найти интересный вопрос
  • Как найти объем тела давления
  • Как найти настоящего парня фильм
  • Как найти управляющего проектом
  • Как быстро найти слизня в майнкрафте