Как найти минимальный элемент в матлабе

Minimum elements of array

Syntax

Description

example

M = min(A)
returns the minimum elements of an array.

  • If A is a vector, then
    min(A) returns the minimum of
    A.

  • If A is a matrix, then
    min(A) is a row vector containing the minimum
    value of each column of A.

  • If A is a multidimensional array, then
    min(A) operates along the first dimension of
    A whose size is greater than
    1, treating the elements as vectors. The size
    of M in this dimension becomes
    1, while the sizes of all other dimensions
    remain the same as in A. If A
    is an empty array whose first has zero length, then
    M is an empty array with the same size as
    A.

  • If A is a
    table or timetable, then min(A) returns a one-row
    table containing the minimum of each variable. (since R2023a)

example

M = min(A,[],"all")
returns the minimum over all elements of A.

example

M = min(A,[],dim)
returns the minimum element along dimension dim. For example,
if A is a matrix, then min(A,[],2) returns
a column vector containing the minimum value of each row.

example

M = min(A,[],vecdim)
returns the minimum over the dimensions specified in the vector
vecdim. For example, if A is a matrix,
then min(A,[],[1 2]) returns the minimum over all elements in
A because every element of a matrix is contained in the
array slice defined by dimensions 1 and 2.

example

M = min(A,[],___,missingflag)
specifies whether to omit or include missing values in A for
any of the previous syntaxes. For example,
min(A,[],"includemissing") includes all missing values
when computing the minimum. By default, min omits missing
values.

example

[M,I] =
min(___)

also returns the index into the operating dimension that corresponds to the
first occurrence of the minimum value of A.

example

[M,I] =
min(A,[],___,"linear")

also returns the linear index into A that corresponds to the
minimum value in A.

example

C = min(A,B)
returns an array with the smallest elements taken from A or
B.

C = min(A,B,missingflag)
also specifies how to treat missing values.

___ = min(___,"ComparisonMethod",method)
optionally specifies how to compare elements for any of the previous syntaxes.
For example, for a vector A = [-1 2 -9], the syntax
min(A,[],"ComparisonMethod","abs") compares the elements
of A according to their absolute values and returns a minimum
value of -1.

Examples

collapse all

Smallest Vector Element

Create a vector and compute its smallest element.

A = [23 42 37 15 52];
M = min(A)

Smallest Complex Element

Create a complex vector and compute its smallest element, that is, the element with the smallest magnitude.

A = [-2+2i 4+i -1-3i];
min(A)

Smallest Element in Each Matrix Column

Create a matrix and compute the smallest element in each column.

Smallest Element in Each Matrix Row

Create a matrix and compute the smallest element in each row.

A = [1.7 1.2 1.5; 1.3 1.6 1.99]
A = 2×3

    1.7000    1.2000    1.5000
    1.3000    1.6000    1.9900

Minimum of Array Page

Create a 3-D array and compute the minimum over each page of data (rows and columns).

A(:,:,1) = [2 4; -2 1];
A(:,:,2) = [9 13; -5 7];
A(:,:,3) = [4 4; 8 -3];
M1 = min(A,[],[1 2])
M1 = 
M1(:,:,1) =

    -2


M1(:,:,2) =

    -5


M1(:,:,3) =

    -3

To compute the minimum over all dimensions of an array, you can either specify each dimension in the vector dimension argument or use the "all" option.

Smallest Element Including Missing Values

Create a matrix containing NaN values.

A = [1.77 -0.005 3.98 -2.95; NaN 0.34 NaN 0.19]
A = 2×4

    1.7700   -0.0050    3.9800   -2.9500
       NaN    0.3400       NaN    0.1900

Compute the minimum value of the matrix, including missing values. For matrix columns that contain any NaN value, the minimum is NaN.

M = min(A,[],"includemissing")
M = 1×4

       NaN   -0.0050       NaN   -2.9500

Smallest Element Indices

Create a matrix A and compute the smallest elements in each column as well as the row indices of A in which they appear.

Return Linear Indices

Create a matrix A and return the minimum value of each row in the matrix M. Use the "linear" option to also return the linear indices I such that M = A(I).

[M,I] = min(A,[],2,"linear")

Smallest Element Comparison

Create a matrix and return the smallest value between each of its elements compared to a scalar.

Input Arguments

collapse all

AInput array
scalar | vector | matrix | multidimensional array | table | timetable

Input array, specified as a scalar, vector, matrix, multidimensional array, table, or
timetable.

  • If A is complex, then min(A) returns
    the complex number with the smallest magnitude. If magnitudes are
    equal, then min(A) returns the value with the smallest
    magnitude and the smallest phase angle.

  • If A is a scalar, then min(A) returns A.

  • If A is a 0-by-0 empty array, then min(A) is
    as well.

If A has type categorical, then it
must be ordinal.

Complex Number Support: Yes

dimDimension to operate along
positive integer scalar

Dimension
to operate along, specified as a positive integer scalar. If you do not specify the dimension,
then the default is the first array dimension of size greater than 1.

Dimension dim indicates the dimension whose
length reduces to 1. The size(M,dim) is 1,
while the sizes of all other dimensions remain the same, unless size(A,dim) is 0.
If size(A,dim) is 0, then min(A,dim) returns
an empty array with the same size as A.

Consider an m-by-n input matrix,
A:

  • min(A,[],1) computes the minimum of the
    elements in each column of A and returns a
    1-by-n row
    vector.

    min(A,[],1) column-wise operation

  • min(A,[],2) computes the minimum of the
    elements in each row of A and returns an
    m-by-1 column
    vector.

    min(A,[],2) row-wise operation

vecdimVector of dimensions
vector of positive integers

Vector of dimensions, specified as a vector of positive integers. Each
element represents a dimension of the input array. The lengths of the output
in the specified operating dimensions are 1, while the others remain the
same.

Consider a 2-by-3-by-3 input array, A. Then
min(A,[],[1 2]) returns a 1-by-1-by-3 array whose
elements are the minimums computed over each page of
A.

Mapping of a 2-by-3-by-3 input array to a 1-by-1-by-3 output array

missingflagMissing value condition
"omitmissing" (default) | "omitnan" | "omitnat" | "omitundefined" | "includemissing" | "includenan" | "includenat" | "includeundefined"

Missing value condition, specified as one of the values in this
table.

Value Input Data Type Description
"omitmissing" All supported data types Ignore missing values in the input arrays,
and compute the minimum over fewer points. If all elements
in the operating dimension are missing, then the
corresponding element in M is
missing.
"omitnan" double, single,
duration
"omitnat" datetime
"omitundefined" categorical
"includemissing" All supported data types

Include missing values in the input
arrays when computing the minimum. If any element in the
operating dimension is missing, then the corresponding
element in M is
missing.

"includenan" double, single,
duration
"includenat" datetime
"includeundefined" categorical

BAdditional input array
scalar | vector | matrix | multidimensional array | table | timetable

Additional input array, specified as a scalar, vector, matrix, multidimensional array, table,
or timetable. Inputs A and B must
either be the same size or have sizes that are compatible (for example,
A is an M-by-N
matrix and B is a scalar or
1-by-N row vector). For more
information, see Compatible Array Sizes for Basic Operations.

  • If A and B are both arrays,
    then they must be the same data type unless one is a
    double. In that case, the data type of the
    other array can be single,
    duration, or any integer type.

  • If A and B are ordinal
    categorical arrays, they must have the same
    sets of categories with the same order.

  • If either A or B is a table
    or timetable, then the other input can be an array, table, or
    timetable.

Complex Number Support: Yes

methodComparison method
"auto" (default) | "real" | "abs"

Comparison method for numeric input, specified as one of these values:

  • "auto" — For a numeric input array
    A, compare elements by
    real(A) when A is real,
    and by abs(A) when A is
    complex.

  • "real" — For a numeric input array
    A, compare elements by
    real(A) when A is real or
    complex. If A has elements with equal real parts,
    then use imag(A) to break ties.

  • "abs" — For a numeric input array
    A, compare elements by
    abs(A) when A is real or
    complex. If A has elements with equal magnitude,
    then use angle(A) in the interval (-π,π] to break
    ties.

Output Arguments

collapse all

M — Minimum values
scalar | vector | matrix | multidimensional array | table

Minimum values, returned as a scalar, vector, matrix, multidimensional array or table.
size(M,dim) is 1, while the sizes
of all other dimensions match the size of the corresponding dimension in
A, unless size(A,dim) is
0. If size(A,dim) is
0, then M is an empty array with
the same size as A.

I — Index
scalar | vector | matrix | multidimensional array | table

Index, returned as a scalar, vector, matrix, multidimensional array, or
table. I is the same size as the first output.

When "linear" is not specified, I is
the index into the operating dimension. When "linear" is
specified, I contains the linear indices of
A corresponding to the minimum values.

If the smallest element occurs more than once, then I
contains the index to the first occurrence of the value.

C — Minimum elements from A or B
scalar | vector | matrix | multidimensional array | table | timetable

Minimum elements from A or B, returned as a scalar,
vector, matrix, multidimensional array, table, or timetable. The size of
C is determined by implicit expansion of the
dimensions of A and B. For more
information, see Compatible Array Sizes for Basic Operations.

The data type of C depends on the data types
of A and B:

  • If A and B are
    the same data type, then C matches the data type
    of A and B.

  • If either A or B is single,
    then C is single.

  • If either A or B is
    an integer data type with the other a scalar double,
    then C assumes the integer data type.

  • If either A or B is a
    table or timetable, then C is a table or
    timetable.

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For
more information, see Tall Arrays.

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

Usage notes and limitations:

  • If you specify an empty array for the second argument in order to
    supply dim or missingflag, the
    second argument must be of fixed-size and of dimension
    0-by-0.

  • If you specify dim or
    missingflag, then they must be constants.

  • If the input is a variable-size array, the length of the dimension to
    operate along must not be zero at run-time.

  • See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).

  • See Code Generation for Complex Data with Zero-Valued Imaginary Parts (MATLAB Coder).

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

Usage notes and limitations:

  • If you specify an empty array for the second argument in order to
    supply dim or missingflag, the
    second argument must be of fixed-size and of dimension
    0-by-0.

  • If you specify dim or
    missingflag, then they must be constants.

  • See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).

  • See Code Generation for Complex Data with Zero-Valued Imaginary Parts (MATLAB Coder).

HDL Code Generation
Generate Verilog and VHDL code for FPGA and ASIC designs using HDL Coder™.

Usage notes and limitations:

  • Inputs of 3-D matrices or greater are not supported.

  • Inputs that have complex data types are not supported.

  • Input matrices or vectors must be of equal size.

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

expand all

R2023a: Specify missing value condition

Omit or include all missing values in the input arrays when computing the minimum
value by using the "omitmissing" or
"includemissing" options. Previously,
"omitnan", "includenan",
"omitnat", "includenat",
"omitundefined", and "includeundefined"
specified a missing value condition that was specific to the data type of the input
arrays.

R2023a: Perform calculations directly on tables and timetables

The min function can calculate on all variables within a table or
timetable without indexing to access those variables. All variables must have data types
that support the calculation. For more information, see Direct Calculations on Tables and Timetables.

R2021b: Specify comparison method

Specify the real or absolute value method for determining the minimum value of the
input by using the ComparisonMethod parameter.

R2018b: Operate on multiple dimensions

Operate on multiple dimensions of the input arrays at a time. Specify a vector of
operating dimensions, or specify the "all" option to operate on
all array dimensions.

min

Smallest element in array of fi objects

Syntax

Description

example

M = min(A) returns the smallest
elements along different dimensions of fi array
A.

  • If A is a vector, min(A)
    returns the smallest element in A.

  • If A is a matrix, min(A)
    treats the columns of A as vectors, returning a row
    vector containing the minimum element from each column.

  • If A is a multidimensional array,
    min operates along the first nonsingleton
    dimension and returns an array of minimum values.

example

M = min(A,[],dim)
returns the smallest elements along dimension dim.

example

[M,I] =
min(___)

finds the indices of the minimum values and returns them in array
I, using any of the input arguments in the previous
syntaxes. If the smallest value occurs multiple times, the index of the first
occurrence is returned.

example

C = min(A,B)
returns an array with the smallest elements taken from A or
B.

Examples

collapse all

Smallest Element in a Vector

Create a fixed-point vector and return the minimum value from the vector.

A = fi([1,5,4,9,2],1,16);
M = min(A)
M = 
     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 11

Minimum Element of Each Matrix Row

Create a matrix of fixed-point values.

A = 
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 10

Find the smallest element of each row by finding the minimum values along the second dimension.

M = 
     2
     5
     6
     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 10

The output, M, is a column vector that contains the smallest element of each row of A.

Minimum Element of Each Matrix Column

Create a fixed-point matrix.

A = 
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 10

Find the smallest element of each column.

M = 
     4     2     3     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 10

The output, M, is a row vector that contains the smallest element of each column of A.

Find the index of each of the minimum elements.

M = 
     4     2     3     1

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 10

Minimum Elements from Two Arrays

Create two fixed-point arrays of the same size.

A = fi([2.3,4.7,6;0,7,9.23],1,16);
B = fi([9.8,3.21,1.6;pi,2.3,1],1,16);

Find the minimum elements from A or B.

C = 
    2.2998    3.2100    1.6001
         0    2.2998    1.0000

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 11

C contains the smallest elements from each pair of corresponding elements in A and B.

Minimum Element of a Complex Vector

Create a complex fixed-point vector, A.

A = fi([1+2i,2+i,3+8i,9+i],1,8)
A = 
   1.0000 + 2.0000i   2.0000 + 1.0000i   3.0000 + 8.0000i   9.0000 + 1.0000i

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 8
        FractionLength: 3

The min function finds the smallest element of a complex vector by taking the element with the smallest magnitude.

ans = 
    2.2500    2.2500    8.5000    9.0000

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 8
        FractionLength: 3

In vector A, the smallest elements, at position 1 and 2, have a magnitude of 2.25. The min function returns the smallest element in output M, and the index of that element in output, I.

M = 
   1.0000 + 2.0000i

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 8
        FractionLength: 3

Although the elements at index 1 and 2 have the same magnitude, the index of the first occurrence of that value is always returned.

Input Arguments

collapse all

AInput fi array
scalar | vector | matrix | multidimensional array

fi or numeric input array, specified as a scalar,
vector, matrix, or multidimensional array. The dimensions of
A and B must match unless one
is a scalar.

The min function ignores
NaNs.

Data Types:
fi|single |
double | int8 |
int16 | int32 |
int64 | uint8 |
uint16 | uint32 |
uint64

Complex Number Support: Yes

BAdditional input array
scalar | vector | matrix | multidimensional array

Additional input fi or numeric array, specified as a
scalar, vector, matrix, or multidimensional array. The dimensions of
A and B must match unless one
is a scalar.

The min function ignores
NaNs.

Data Types:
fi|single |
double | int8 |
int16 | int32 |
int64 | uint8 |
uint16 | uint32 |
uint64

Complex Number Support: Yes

dimdimension to operate along
positive integer scalar

Dimension to operate along, specified as a positive integer scalar. dim
can also be a fi object. If you do not specify a value,
the default value is the first array dimension whose size does not equal
1.

Data Types: fi|single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Output Arguments

collapse all

M — Minimum values
scalar | vector | matrix | multidimensional array

Minimum values, returned as a scalar, vector, matrix, or multidimensional
array. M always has the same data type as the
input.

I — Index
scalar | vector | matrix | multidimensional array

Index, returned as a scalar, vector, matrix, or multidimensional array. If
the smallest value occurs more than once, then I
contains the index to the first occurrence of the value.
I is always of data type
double.

C — Minimum elements from A or B
scalar | vector | matrix | multidimensional array

Minimum elements from A or B,
returned as a scalar, vector, matrix, or multidimensional array.

Algorithms

When A or B is complex, the min
function returns the element with the smallest magnitude. If two magnitudes are equal,
then min returns the first value. This behavior differs from how the
built-in min function resolves ties between
complex numbers.

Extended Capabilities

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

HDL Code Generation
Generate Verilog and VHDL code for FPGA and ASIC designs using HDL Coder™.

Version History

Introduced before R2006a

Минимальные элементы массива

Синтаксис

Описание

пример

M = min(A) возвращает минимальные элементы массива.

  • Если A вектор, затем min(A) возвращает минимум A.

  • Если A матрица, затем min(A) вектор-строка, содержащий минимальное значение каждого столбца.

  • Если A многомерный массив, затем min(A) действует вдоль первого измерения массива, размер которого не равняется 1, обработка элементов как векторы. Размер этой размерности становится 1 в то время как размеры всех других размерностей остаются то же самое. Если A пустой массив с первой размерностью 0, затем min(A) возвращает пустой массив с тем же размером как A.

пример

M = min(A,[],dim) возвращает минимальный элемент по измерению dim. Например, если A матрица, затем min(A,[],2) вектор-столбец, содержащий минимальное значение каждой строки.

пример

M = min(A,[],nanflag) задает, включать ли или не использовать NaN значения в вычислении. Например, min(A,[],'includenan') включает весь NaN значения в A в то время как min(A,[],'omitnan') игнорирует их.

M = min(A,[],dim,nanflag) также задает размерность, которую задает направление расчета при использовании nanflag опция.

пример

[M,I] =
min(___)
также возвращает индекс в операционную размерность, которая соответствует минимальному значению A для любого из предыдущих синтаксисов.

пример

M = min(A,[],'all') находит минимум по всем элементам A. Этот синтаксис допустим для MATLAB® версии R2018b и позже.

пример

M = min(A,[],vecdim) вычисляет минимум по размерностям, заданным в векторном vecdim. Например, если A матрица, затем min(A,[],[1 2]) вычисляет минимум по всем элементам в A, поскольку каждый элемент матрицы содержится в срезе массивов, заданном размерностями 1 и 2.

M = min(A,[],'all',nanflag) вычисляет минимум по всем элементам A при использовании nanflag опция.

M = min(A,[],vecdim,nanflag) задает несколько размерностей, которых задают направление расчета при использовании nanflag опция.

[M,I] =
min(A,[],'all',___)
возвращает линейный индекс в A это соответствует минимальному значению в A при определении 'all'.

пример

[M,I] =
min(A,[],___,'linear')
возвращает линейный индекс в A это соответствует минимальному значению в A.

пример

C = min(A,B) возвращает массив с самыми маленькими элементами, взятыми из A или B.

C = min(A,B,nanflag) также задает, как обработать NaN значения.

___ = min(___,'ComparisonMethod',method) опционально задает, как сравнить элементы для любого из предыдущих синтаксисов. Например, для векторного A = [-1 2 -9], синтаксис min(A,[],'ComparisonMethod','abs') сравнивает элементы A согласно их абсолютным значениям и возвращает -1.

Примеры

свернуть все

Самый маленький векторный элемент

Создайте вектор и вычислите его самый маленький элемент.

A = [23 42 37 15 52];
M = min(A)

Самый маленький комплексный элемент

Создайте комплексный вектор и вычислите его самый маленький элемент, то есть, элемент с наименьшей величиной.

A = [-2+2i 4+i -1-3i];
min(A)

Самый маленький элемент в каждом столбце матрицы

Создайте матрицу и вычислите самый маленький элемент в каждом столбце.

Самый маленький элемент в каждой матричной строке

Создайте матрицу и вычислите самый маленький элемент в каждой строке.

A = [1.7 1.2 1.5; 1.3 1.6 1.99]
A = 2×3

    1.7000    1.2000    1.5000
    1.3000    1.6000    1.9900

Самое маленькое включение элемента NaN

Создайте вектор и вычислите его минимум, исключая NaN значения.

A = [1.77 -0.005 3.98 -2.95 NaN 0.34 NaN 0.19];
M = min(A,[],'omitnan')

min(A) также приведет к этому результату начиная с 'omitnan' опция по умолчанию.

Используйте 'includenan' отметьте, чтобы возвратить NaN.

M = min(A,[],'includenan')

Самые маленькие индексы элемента

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

Минимум страницы массивов

Создайте трехмерный массив и вычислите минимум по каждой странице данных (строки и столбцы).

A(:,:,1) = [2 4; -2 1];
A(:,:,2) = [9 13; -5 7];
A(:,:,3) = [4 4; 8 -3];
M1 = min(A,[],[1 2])
M1 = 
M1(:,:,1) =

    -2


M1(:,:,2) =

    -5


M1(:,:,3) =

    -3

Начиная в R2018b, вычислять минимум по всем размерностям массива, можно или задать каждую размерность в векторном аргументе размерности или использовать 'all' опция.

Возвратите линейные индексы

Создайте матричный A и возвратите минимальное значение каждой строки в матричном M. Используйте 'linear' опция, чтобы также возвратить линейные индексы I таким образом, что M = A(I).

[M,I] = min(A,[],2,'linear')

Самое маленькое сравнение элемента

Создайте матрицу и возвратите наименьшее значение между каждым из его элементов по сравнению со скаляром.

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

свернуть все

AВходной массив
скаляр | вектор | матрица | многомерный массив

Входной массив, заданный как скалярный, векторный, матричный или многомерный массив.

  • Если A является комплексным, затем min(A) возвращает комплексное число с наименьшей величиной. Если величины равны, то min(A) возвращает значение с наименьшей величиной и самым маленьким углом фазы.

  • Если A скаляр, затем min(A) возвращает A.

  • Если A пустой массив 0 на 0, затем min(A) также.

Если A имеет вводят categorical, затем это должно быть порядковым.

Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | categorical | datetime | duration
Поддержка комплексного числа: Да

dimРазмерность, которая задает направление расчета
положительный целочисленный скаляр

Величина для работы, заданная как положительный целый скаляр. Если значение не задано, то по умолчанию это первый размер массива, не равный 1.

Размерность dim указывает на размерность, длина которой уменьшает до 1. size(M,dim) 1, в то время как размеры всех других размерностей остаются то же самое, если size(A,dim) 0. Если size(A,dim) 0, затем min(A,dim) возвращает пустой массив с тем же размером как A.

Рассмотрите двумерный входной массив, A:

  • Если dim = 1, затем min(A,[],1) возвращает вектор-строку, содержащий самый маленький элемент в каждом столбце.

  • Если dim = 2, затем min(A,[],2) возвращает вектор-столбец, содержащий самый маленький элемент в каждой строке.

min возвращает A если dim больше ndims(A).

vecdimВектор из размерностей
вектор из положительных целых чисел

Вектор из размерностей в виде вектора из положительных целых чисел. Каждый элемент представляет размерность входного массива. Продолжительности выхода в заданных операционных размерностях равняются 1, в то время как другие остаются то же самое.

Рассмотрите 2 3х3 входным массивом, A. Затем min(A,[],[1 2]) возвращает 1 1 3 массивами, элементами которых являются минимумы, вычисленные по каждой странице A.

Типы данных: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

BДополнительный входной массив
скаляр | вектор | матрица | многомерный массив

Дополнительный входной массив в виде скаляра, вектора, матрицы или многомерного массива. Входные параметры A и B должен или быть одного размера или иметь размеры, которые совместимы (например, A MN матрица и B скаляр или 1N вектор-строка). Для получения дополнительной информации см. “Совместимые размеры массивов для основных операций”.

  • A и B должен быть совпадающий тип данных, если каждый не double. В этом случае типом данных другого массива может быть singleдлительность, или любой целочисленный тип.

  • Если A и B порядковый categorical массивы, у них должны быть те же наборы категорий с тем же порядком.

Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | categorical | datetime | duration
Поддержка комплексного числа: Да

nanflag NaN условие
'omitnan' (значение по умолчанию) | 'includenan'

NaN условие в виде одного из этих значений:

  • 'omitnan' — Проигнорируйте весь NaN значения во входе. Если всеми элементами является NaN, затем min возвращает первый.

  • 'includenan' — Включайте NaN значения во входе для вычисления.

Для datetime массивы, можно также использовать 'omitnat' или 'includenat' не использовать и включать NaT значения, соответственно.

Для categorical массивы, можно также использовать 'omitundefined' или 'includeundefined' не использовать и включать неопределенные значения, соответственно.

Типы данных: char

method ‘ComparisonMethod’
'auto' (значение по умолчанию) | 'real' | 'abs'

Метод сравнения для числового входа в виде одного из этих значений:

  • 'auto' — Для числового входного массива A, сравните элементы real(A) когда A действительно, и abs(A) когда A является комплексным.

  • 'real' — Для числового входного массива A, сравните элементы real(A) когда A является действительным или комплексным. Если A имеет элементы с равными действительными частями, затем используйте imag(A) повредить связи.

  • 'abs' — Для числового входного массива A, сравните элементы abs(A) когда A является действительным или комплексным. Если A имеет элементы с равной величиной, затем используйте angle(A) в интервале (-π,π], чтобы повредить связи.

Выходные аргументы

свернуть все

M — Минимальные значения
скаляр | вектор | матрица | многомерный массив

Минимальные значения, возвращенные как скаляр, вектор, матрица или многомерный массив. size(M,dim) 1, в то время как размеры всех других размерностей совпадают с размером соответствующей размерности в A, если size(A,dim) 0. Если size(A,dim) 0, затем M пустой массив с тем же размером как A.

I — Индекс
скаляр | вектор | матрица | многомерный массив

Индексируйте, возвращенный как скаляр, вектор, матрица или многомерный массив. I одного размера с первым выходом.

Когда 'linear' не задан, I индекс в операционную размерность. Когда 'linear' задан, I содержит линейные индексы A соответствие минимальным значениям.

Если самый маленький элемент происходит несколько раз, то I содержит индекс к первому вхождению значения.

C — Минимальные элементы от A или B
скаляр | вектор | матрица | многомерный массив

Минимальные элементы от A или B, возвращенный как скаляр, вектор, матрица или многомерный массив. Размер C определяется неявным расширением размерностей A и BДля получения дополнительной информации см. “Совместимые размеры массивов для основных операций”.

Тип данных C зависит от типов данных A и B:

  • Если A и B совпадающий тип данных, затем C совпадает с типом данных A и B.

  • Если любой A или B single, затем C single.

  • Если любой A или B целочисленный тип данных с другим скалярный double, затем C принимает целочисленный тип данных.

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

“Высокие” массивы
Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.

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

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

  • Если вы задаете пустой массив для второго аргумента для того, чтобы предоставить dim или nanflag, второй аргумент должен иметь фиксированный размер и размерности 00.

  • Если вы задаете dim или nanflag, затем они должны быть константами.

  • Если вход является массивом переменного размера, длина размерности, которой задает направление расчета не должна быть нулем во времени выполнения.

  • “Смотрите информацию о генерации кода функций Toolbox (MATLAB Coder) в разделе “”Ограничения переменных размеров””.”.

  • Смотрите генерацию кода для комплексных данных с мнимыми частями с нулевым знаком (MATLAB Coder).

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

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

  • Если вы задаете пустой массив для второго аргумента для того, чтобы предоставить dim или nanflag, второй аргумент должен иметь фиксированный размер и размерности 00.

  • Если вы задаете dim или nanflag, затем они должны быть константами.

  • “Смотрите информацию о генерации кода функций Toolbox (MATLAB Coder) в разделе “”Ограничения переменных размеров””.”.

  • Смотрите генерацию кода для комплексных данных с мнимыми частями с нулевым знаком (MATLAB Coder).

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

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

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

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

Распределенные массивы
Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.

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

Представлено до 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;

Here are two possible solutions. Both essentially involve converting all non-available costs to Inf.

%#Set up an example
Cost =      [0.2 0 0.3; 0.4 0 0; 0.5 0 0];
Available = [1   1   0; 1   0 0; 0   0 0];

%#Transform non-available costs to Inf
Cost(Available == 0) = Inf;

%#Obtain indices using find
[r, c] = find(Cost == min(min(Cost)))

%#Obtain linear indices and convert using ind2sub
[~, I1] = min(Cost(:));
[r2, c2] = ind2sub(size(Cost), I1);

Both solutions will only return the first minimum value in the instance that there is not a unique minimum. Also, the method will fail in the perverse case that all the available costs are Inf (but I guess you’ve got bigger problems if all your costs are infinite…).

I’ve done a few speed tests, and the second method is definitely faster, no matter what the dimensions of Cost, so should be strictly preferred. Also, if you only want linear indices and not subscript indices then you can of course drop the call to ind2sub. However, this doesn’t give you huge savings in efficiency, so if there is a preference for subscript indices then you should use them.

Добавить комментарий