Как найти длину вектора в матлабе

Main Content

Length of largest array dimension

Syntax

Description

example

L = length(X) returns
the length of the largest array dimension in X.
For vectors, the length is simply the number of elements. For arrays
with more dimensions, the length is max(size(X)).
The length of an empty array is zero.

Examples

collapse all

Number of Vector Elements

Find the length of a uniformly spaced vector in the interval [5,10].

Length of Rectangular Matrix

Find the length of a 3-by-7 matrix of zeros.

X = zeros(3,7);
L = length(X)

String Array

Create a string array and compute its length, which is the number of elements in each row.

X = ["a" "b" "c"; "d" "e" "f"]
X = 2x3 string
    "a"    "b"    "c"
    "d"    "e"    "f"

Length of Structure Fields

Create a structure with fields for Day and Month. Use the structfun function to apply length to each field.

S = struct('Day',[1 13 14 26],'Month',{{'Jan','Feb', 'Mar'}})
S = struct with fields:
      Day: [1 13 14 26]
    Month: {'Jan'  'Feb'  'Mar'}

L = structfun(@(field) length(field),S)

Input Arguments

collapse all

XInput array
scalar | vector | matrix | multidimensional array

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

Complex Number Support: Yes

Tips

  • To find the number of characters in a string or character vector, use the
    strlength function.

  • length does not operate on tables. To examine the
    dimensions of a table, use the height,
    width, or size functions.

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™.

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

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

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

·       
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;

length

Длина самого большого измерения массива

Синтаксис

Описание

пример

L = length(X) возвращает длину самого большого измерения массива в X. Для векторов длина является просто числом элементов. Для массивов с большим количеством размерностей длиной является max(size(X)). Длина пустого массива является нулем.

Примеры

свернуть все

Количество векторных элементов

Найдите длину однородно расположенного с интервалами вектора в интервале [5,10].

Длина прямоугольной матрицы

Найдите длину 3 7 матрица нулей.

X = zeros(3,7);
L = length(X)

Массив строк

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

X = ["a" "b" "c"; "d" "e" "f"]
X = 2x3 string
    "a"    "b"    "c"
    "d"    "e"    "f"

Длина полей структуры

Создайте структуру с полями для Day и Month. Используйте structfun функция, чтобы применить length к каждому полю.

S = struct('Day',[1 13 14 26],'Month',{{'Jan','Feb', 'Mar'}})
S = struct with fields:
      Day: [1 13 14 26]
    Month: {'Jan'  'Feb'  'Mar'}

L = structfun(@(field) length(field),S)

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

свернуть все

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

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

Поддержка комплексного числа: Да

Советы

  • Чтобы найти количество символов в строке или векторе символов, используйте strlength функция.

  • length не работает с таблицами. Чтобы исследовать размерности таблицы, используйте heightwidth, или size функции.

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

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

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

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

Генерация HDL-кода
Сгенерируйте Verilog и код VHDL для FPGA и проекты ASIC с помощью HDL Coder™.

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

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

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

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

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

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

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

  1. Get Size of a Vector Using the size() Function in MATLAB
  2. Get the Number of Elements Present in a Vector Using the length() Function in MATLAB
  3. Get the Number of Elements Present in a Vector or Matrix Using the numel() Function in MATLAB

Get the Size of Vector in Matlab

In this tutorial, we will discuss how to get the size and the number of elements present in a vector using the length(), size(), and numel() functions in MATLAB.

Get Size of a Vector Using the size() Function in MATLAB

The size() function returns the number of rows and columns present in a vector or matrix. For example, let’s get the size of a vector. See the code below.

vector = [1 2 3 4];
s = size(vector)

Output:

As you can see, the size of the given vector is 1x4. This method is only suitable for finding the size of a vector and not suitable for finding the number of elements as it returns the number of rows and columns.

Get the Number of Elements Present in a Vector Using the length() Function in MATLAB

The length() function returns the number of elements present in a vector. For example, let’s get the length of a vector. See the code below.

vector = [1 2 3 4];
len = length(vector)

Output:

As you can see, the length of the given vector is 4. This method is only suitable for finding the number of elements present in a vector and not suitable for finding the number of elements in a matrix as it returns only the longest dimension.

Get the Number of Elements Present in a Vector or Matrix Using the numel() Function in MATLAB

The numel() function returns the number of elements present in a vector or matrix. For example, let’s get the number of elements present in a matrix. See the code below.

vector = [1 2 3 4; 1 2 3 4];
len = numel(vector)

Output:

As you can see, the length or number of elements present in the given vector is 8. This method is suitable for finding the number of elements present in a vector or matrix.

Main Content

Length of largest array dimension

Syntax

Description

example

L = length(X) returns
the length of the largest array dimension in X.
For vectors, the length is simply the number of elements. For arrays
with more dimensions, the length is max(size(X)).
The length of an empty array is zero.

Examples

collapse all

Number of Vector Elements

Find the length of a uniformly spaced vector in the interval [5,10].

Length of Rectangular Matrix

Find the length of a 3-by-7 matrix of zeros.

X = zeros(3,7);
L = length(X)

String Array

Create a string array and compute its length, which is the number of elements in each row.

X = ["a" "b" "c"; "d" "e" "f"]
X = 2x3 string
    "a"    "b"    "c"
    "d"    "e"    "f"

Length of Structure Fields

Create a structure with fields for Day and Month. Use the structfun function to apply length to each field.

S = struct('Day',[1 13 14 26],'Month',{{'Jan','Feb', 'Mar'}})
S = struct with fields:
      Day: [1 13 14 26]
    Month: {'Jan'  'Feb'  'Mar'}

L = structfun(@(field) length(field),S)

Input Arguments

collapse all

XInput array
scalar | vector | matrix | multidimensional array

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

Complex Number Support: Yes

Tips

  • To find the number of characters in a string or character vector, use the
    strlength function.

  • length does not operate on tables. To examine the
    dimensions of a table, use the height,
    width, or size functions.

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™.

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

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

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

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