Syntax
Description
example
returns the standardS
= std(A
)
deviation of the elements of A
along the first array dimension
whose size does not equal 1. By default, the standard deviation is normalized by
N-1
, where N
is the number of
observations.
-
If
A
is a vector of observations, then
S
is a scalar. -
If
A
is a matrix whose columns are random variables and
whose rows are observations, thenS
is a row vector
containing the standard deviation corresponding to each column. -
If
A
is a multidimensional array, then
std(A)
operates along the first array dimension whose
size does not equal 1, treating the elements as vectors. The size of
S
in this dimension becomes1
while the sizes of all other dimensions are the same as
A
. -
If
A
is a scalar, thenS
is
0
. -
If
A
is a0
-by-0
empty array, thenS
isNaN
.
example
S
= std(A
,w
)
specifies a weighting scheme. When w = 0
(default), the standard
deviation is normalized by N-1
, where N
is the
number of observations. When w = 1
, the standard deviation is
normalized by the number of observations. w
also can be a weight
vector containing nonnegative elements. In this case, the length of
w
must equal the length of the dimension over which
std
is operating.
S
= std(A
,w
,"all"
)
computes the standard deviation over all elements of A
when
w
is either 0 or 1. This syntax is valid for MATLAB® versions R2018b and later.
example
S
= std(A
,w
,dim
)
returns the standard deviation along dimension dim
. To maintain
the default normalization while specifying the dimension of operation, set
w = 0
in the second argument.
example
S
= std(A
,w
,vecdim
)
computes the standard deviation over the dimensions specified in the vector
vecdim
when w
is 0 or 1. For example, if
A
is a matrix, then std(A,0,[1 2])
computes the standard deviation over all elements in A
, since
every element of a matrix is contained in the array slice defined by dimensions 1
and 2.
example
S
= std(___,nanflag
)
specifies whether to include or omit NaN
values from the
calculation for any of the previous syntaxes. For example,
std(A,"includenan")
includes all NaN
values in A
while std(A,"omitnan")
ignores
them.
Examples
collapse all
Standard Deviation of Matrix Columns
Create a matrix and compute the standard deviation of each column.
A = [4 -5 1; 2 3 5; -9 1 7]; S = std(A)
S = 1×3
7.0000 4.1633 3.0551
Standard Deviation of 3-D Array
Create a 3-D array and compute the standard deviation along the first dimension.
A(:,:,1) = [2 4; -2 1]; A(:,:,2) = [9 13; -5 7]; A(:,:,3) = [4 4; 8 -3]; S = std(A)
S = S(:,:,1) = 2.8284 2.1213 S(:,:,2) = 9.8995 4.2426 S(:,:,3) = 2.8284 4.9497
Specify Standard Deviation Weights
Create a matrix and compute the standard deviation of each column according to a weight vector w
.
A = [1 5; 3 7; -9 2]; w = [1 1 0.5]; S = std(A,w)
Standard Deviation Along Matrix Rows
Create a matrix and compute the standard deviation along each row.
A = [6 4 23 -3; 9 -10 4 11; 2 8 -5 1]; S = std(A,0,2)
S = 3×1
11.0303
9.4692
5.3229
Standard Deviation of Array Page
Create a 3-D array and compute the standard deviation 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]; S = std(A,0,[1 2])
S = S(:,:,1) = 2.5000 S(:,:,2) = 7.7460 S(:,:,3) = 4.5735
Standard Deviation Excluding NaN
Create a vector and compute its standard deviation, excluding NaN
values.
A = [1.77 -0.005 3.98 -2.95 NaN 0.34 NaN 0.19];
S = std(A,"omitnan")
Standard Deviation and Mean
Create a matrix and compute the standard deviation and mean of each column.
A = [4 -5 1; 2 3 5; -9 1 7]; [S,M] = std(A)
S = 1×3
7.0000 4.1633 3.0551
M = 1×3
-1.0000 -0.3333 4.3333
Create a matrix and compute the weighted standard deviation and weighted mean of each column according to a weight vector w
.
A = [1 5; 3 7; -9 2]; w = [1 1 0.5]; [S,M] = std(A,w)
Input Arguments
collapse all
A
— Input array
vector | matrix | multidimensional array
Input array, specified as a vector, matrix, or multidimensional
array. If A
is a scalar, then std(A)
returns 0
.
If A
is a 0
-by-0
empty
array, then std(A)
returns NaN
.
Data Types: single
| double
| datetime
| duration
Complex Number Support: Yes
w
— Weight
0
(default) | 1
| vector
Weight, specified as one of these values:
-
0
— Normalize by
N-1
, whereN
is the
number of observations. If there is only one observation, then
the weight is 1. -
1
— Normalize byN
. -
Vector made up of nonnegative scalar weights corresponding
to the dimension ofA
along which the standard
deviation is calculated.
Data Types: single
| double
dim
— Dimension 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(S,dim)
is 1
,
while the sizes of all other dimensions remain the same.
Consider an m
-by-n
input matrix,
A
:
-
std(A,0,1)
computes the standard deviation
of the elements in each column ofA
and
returns a1
-by-n
row
vector. -
std(A,0,2)
computes the standard deviation
of the elements in each row ofA
and returns
anm
-by-1
column
vector.
If dim
is greater than ndims(A)
,
then std(A)
returns an array of zeros the same
size as A
.
vecdim
— Vector 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
std(A,0,[1 2])
returns a 1-by-1-by-3 array whose
elements are the standard deviations computed over each page of
A
.
nanflag
— NaN
condition
"includenan"
(default) | "omitnan"
| "includenat"
| "omitnat"
NaN
condition, specified as one of these
values:
-
"includenan"
— Include
NaN
values when computing the standard
deviation, resulting inNaN
. -
"omitnan"
— Ignore
NaN
values appearing in either the input
array or weight vector. -
"includenat"
— Include
NaT
values when computing the standard
deviation fordatetime
arrays. -
"omitnat"
— Ignore
NaT
values appearing in either the input
array or weight vector fordatetime
arrays.
Output Arguments
collapse all
S
— Standard deviation
scalar | vector | matrix | multidimensional array
Standard deviation, returned as a scalar, vector, matrix, or
multidimensional array.
-
If
A
is a vector of observations, then
S
is a scalar. -
If
A
is a matrix whose columns are random
variables and whose rows are observations, then
S
is a row vector containing the standard
deviation corresponding to each column. -
If
A
is a multidimensional array, then
std(A)
operates along the first array
dimension whose size does not equal 1, treating the elements as
vectors. The size ofS
in this dimension
becomes1
while the sizes of all other
dimensions are the same asA
. -
If
A
is a scalar, thenS
is0
. -
If
A
is a
0
-by-0
empty array,
thenS
isNaN
.
M
— Mean
scalar | vector | matrix | multidimensional array
Mean, returned as a scalar, vector, matrix, or multidimensional array.
-
If
A
is a vector of observations, then
M
is a scalar. -
If
A
is a matrix whose columns are random
variables and whose rows are observations, then
M
is a row vector containing the mean
corresponding to each column. -
If
A
is a multidimensional array, then
std(A)
operates along the first array
dimension whose size does not equal 1, treating the elements as
vectors. The size ofM
in this dimension
becomes1
while the sizes of all other
dimensions are the same asA
. -
If
A
is a scalar, thenM
is equal toA
. -
If
A
is a
0
-by-0
empty array,
thenM
isNaN
.
If S
is the weighted standard deviation, then
M
is the weighted mean.
More About
collapse all
Standard Deviation
For a finite-length vector A made up of
N scalar observations, the standard deviation is defined as
where μ is the mean of A:
The standard deviation is the square root of the variance.
Some definitions of standard deviation use a normalization factor
N instead of N – 1. You can use a
normalization factor of N by specifying a weight of
1
, producing the square root of the second moment of the
sample about its mean.
Regardless of the normalization factor for the standard
deviation, the mean is assumed to have the normalization factor
N.
Weighted Standard Deviation
For a finite-length vector A made up of
N scalar observations and weighting scheme
w
, the weighted standard deviation is defined as
where μw is the weighted
mean of A.
Weighted Mean
For a random variable vector A made up of
N scalar observations and weighting scheme
w
, the weighted mean is defined as
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function supports tall arrays with the limitation:
-
The weighting scheme cannot be a vector.
For more information, see Tall Arrays for Out-of-Memory Data.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
-
C++ code generation supports the following syntaxes:
-
S = std(A)
-
S = std(A,w)
-
S = std(A,w,"all")
-
S = std(A,w,dim)
-
S = std(A,w,vecdim)
-
S = std(__,nanflag)
-
-
When specified, dimension must be a constant.
-
See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Usage notes and limitations:
-
GPU code generation supports the following syntaxes:
-
S = std(A)
-
S = std(A,w)
-
S = std(A,w,"all")
-
S = std(A,w,dim)
-
S = std(A,w,vecdim)
-
S = std(__,nanflag)
-
-
If you specify
dim
, then it must be a
constant.
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
R2022a: Return mean or weighted mean
The std
function can now return the mean of the input
elements used to calculate the standard deviation by using a second output argument
M
. If a weighting scheme is specified, then
std
returns the weighted
mean.
It’s possible to calculate the standard error in MATLAB by running a one-line command. MATLAB is a programming platform from MathWorks that’s designed for and used by scientists and engineers.
What Is Standard Error?
In statistics, the standard error is the standard deviation of the sampling statistical measure, and it’s most commonly used for the sample mean. The standard error measures how accurately the sample represents the actual population from which the sample was drawn.
Since there could be different samples drawn from the population, there exists a distribution of sampled means. The standard error measures the standard deviation of all sample means drawn from the population.
The formula for calculating the standard error of the mean is the sample standard deviation divided by the square root of the sample size.
The Command for Standard Error in MATLAB
To calculate the standard error of the mean in a sample, the user needs to run a one-line command in MATLAB:
stderror
=
std( data ) / sqrt( length( data ))
where:
data
=
An array with sample values
std
=
The MATLAB function that computes standard
deviation of the sample
sqrt
=
The MATLAB function that computes the square
root of a non-negative number
length
=
The MATLAB function that computes the total
number of observations in the sample
begin{aligned} &text{stderror} = text{ std( data ) / sqrt( length( data ))}\ &textbf{where:}\ &text{data} = text{An array with sample values}\ &text{std} = text{The MATLAB function that computes standard} \ &text{deviation of the sample}\ &text{sqrt} = text{The MATLAB function that computes the square} \ &text{root of a non-negative number}\ &text{length} = text{The MATLAB function that computes the total} \ &text{number of observations in the sample}\ end{aligned}
stderror= std( data ) / sqrt( length( data ))where:data=An array with sample valuesstd=The MATLAB function that computes standarddeviation of the samplesqrt=The MATLAB function that computes the squareroot of a non-negative numberlength=The MATLAB function that computes the totalnumber of observations in the sample
Example of Calculating Standard Error in MATLAB
Consider a sample of annual household incomes drawn from the general population of the United States. The sample contains five observations and consists of values $10,000, $100,000, $50,000, $45,000 and $35,000.
First, the user needs to create an array called «data» containing these observations in MATLAB. Next, the user can calculate the standard error of the mean with the command «stderror = std( data ) / sqrt( length )». The result of this command says that the mean of this sample, which is $48,000, has a standard error of $13,161.
std
Синтаксис
Описание
пример
S = std(
возвращает стандартное отклонение элементов A
)A
вдоль первого измерения массива, размер которого не равняется 1.
-
Если
A
вектор из наблюдений, затем стандартное отклонение является скаляром. -
Если
A
матрица, столбцы которой являются случайными переменными и чьи строки являются наблюдениями, затемS
вектор-строка, содержащий стандартные отклонения, соответствующие каждому столбцу. -
Если
A
многомерный массив, затемstd(A)
действует вдоль первого измерения массива, размер которого не равняется 1, обрабатывая элементы как векторы. Размер этой размерности становится1
в то время как размеры всех других размерностей остаются то же самое. -
По умолчанию стандартное отклонение нормировано на
N-1
, гдеN
количество наблюдений.
пример
S = std(
задает схему взвешивания любого из предыдущих синтаксисов. Когда A
,w
)w = 0
(значение по умолчанию), S
нормирован на N-1
. Когда w = 1
S
нормирован на количество наблюдений, N
W
также может быть вектор веса, содержащий неотрицательные элементы. В этом случае, длина w
должен равняться длине размерности по который std
действует.
S = std(
вычисляет стандартное отклонение по всем элементам A
,w
,'all'
)A
когда w
или 0 или 1. Этот синтаксис допустим для MATLAB® версии R2018b и позже.
пример
S = std(
возвращает стандартное отклонение по измерению A
,w
,dim
)dim
для любого из предыдущих синтаксисов. Чтобы обеспечить нормализацию по умолчанию при определении размерности операции, установите w = 0
во втором аргументе.
пример
S = std(
вычисляет стандартное отклонение по размерностям, заданным в векторном A
,w
,vecdim
)vecdim
когда w
0 или 1. Например, если A
матрица, затем std(A,0,[1 2])
вычисляет стандартное отклонение по всем элементам в A
, поскольку каждый элемент матрицы содержится в срезе массивов, заданном размерностями 1 и 2.
пример
S = std(___,
задает, включать ли или не использовать nanflag
)NaN
значения от вычисления для любого из предыдущих синтаксисов. Например, std(A,'includenan')
включает весь NaN
значения в A
в то время как std(A,'omitnan')
игнорирует их.
Примеры
свернуть все
Стандартное отклонение столбцов матрицы
Создайте матрицу и вычислите стандартное отклонение каждого столбца.
A = [4 -5 1; 2 3 5; -9 1 7]; S = std(A)
S = 1×3
7.0000 4.1633 3.0551
Стандартное отклонение трехмерного массива
Создайте трехмерный массив и вычислите стандартное отклонение по первому измерению.
A(:,:,1) = [2 4; -2 1]; A(:,:,2) = [9 13; -5 7]; A(:,:,3) = [4 4; 8 -3]; S = std(A)
S = S(:,:,1) = 2.8284 2.1213 S(:,:,2) = 9.8995 4.2426 S(:,:,3) = 2.8284 4.9497
Определение весов стандартного отклонения
Создайте матрицу и вычислите стандартное отклонение каждого столбца согласно вектору веса w
.
A = [1 5; 3 7; -9 2]; w = [1 1 0.5]; S = std(A,w)
Стандартное отклонение вдоль матричных строк
Создайте матрицу и вычислите стандартное отклонение вдоль каждой строки.
A = [6 4 23 -3; 9 -10 4 11; 2 8 -5 1]; S = std(A,0,2)
S = 3×1
11.0303
9.4692
5.3229
Стандартное отклонение страницы массивов
Создайте трехмерный массив и вычислите стандартное отклонение по каждой странице данных (строки и столбцы).
A(:,:,1) = [2 4; -2 1]; A(:,:,2) = [9 13; -5 7]; A(:,:,3) = [4 4; 8 -3]; S = std(A,0,[1 2])
S = S(:,:,1) = 2.5000 S(:,:,2) = 7.7460 S(:,:,3) = 4.5735
Стандартное отклонение, исключая NaN
Создайте вектор и вычислите его стандартное отклонение, исключая NaN
значения.
A = [1.77 -0.005 3.98 -2.95 NaN 0.34 NaN 0.19];
S = std(A,'omitnan')
Входные параметры
свернуть все
A
— Входной массив
вектор | матрица | многомерный массив
Входной массив, заданный как векторный, матричный или многомерный массив. Если A
скаляр, затем std(A)
возвращает 0
. Если A
0
— 0
пустой массив, затем std(A)
возвращает NaN
.
Типы данных: single
| double
| datetime
| duration
Поддержка комплексного числа: Да
w
— Вес
0
(значение по умолчанию) | 1
| вектор
Вес в виде одного из этих значений:
-
0
— Нормируйте на
N-1
, гдеN
количество наблюдений. Если существует только одно наблюдение, то вес равняется 1. -
1
— Нормируйте на
N
. -
Вектор, составленный из неотрицательных скалярных весов, соответствующих размерности
A
вдоль которого вычисляется стандартное отклонение.
Типы данных: single
| double
dim
— Размерность, которая задает направление расчета
положительный целочисленный скаляр
Величина для работы, заданная как положительный целый скаляр. Если значение не задано, то по умолчанию это первый размер массива, не равный 1.
Размерность dim
указывает на размерность, длина которой уменьшает до 1
. size(S,dim)
1
, в то время как размеры всех других размерностей остаются то же самое.
Рассмотрите двумерный входной массив, A
.
-
Если
dim = 1
, затемstd(A,0,1)
возвращает вектор-строку, содержащий стандартное отклонение элементов в каждом столбце. -
Если
dim = 2
, затемstd(A,0,2)
возвращает вектор-столбец, содержащий стандартное отклонение элементов в каждой строке.
Если dim
больше ndims(A)
, затем std(A)
возвращает массив нулей тот же размер как A
.
Типы данных: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
vecdim
— Вектор из размерностей
вектор из положительных целых чисел
Вектор из размерностей в виде вектора из положительных целых чисел. Каждый элемент представляет размерность входного массива. Продолжительности выхода в заданных операционных размерностях равняются 1, в то время как другие остаются то же самое.
Рассмотрите 2 3х3 входным массивом, A
. Затем std(A,0,[1 2])
возвращает 1 1 3 массивами, элементами которых являются стандартные отклонения, вычисленные по каждой странице A
.
Типы данных: double |
single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
nanflag
NaN
условие
'includenan'
(значение по умолчанию) | 'omitnan'
NaN
условие в виде одного из этих значений:
-
'includenan'
— ВключайтеNaN
значения при вычислении стандартного отклонения, приведении кNaN
. -
'omitnan'
— ПроигнорируйтеNaN
значения, появляющиеся или во входном массиве или в векторе веса.
Для datetime
массивы, можно также использовать 'omitnat'
или 'includenat'
не использовать и включать NaT
значения, соответственно.
Типы данных: char
Больше о
свернуть все
Стандартное отклонение
Для вектора случайной переменной A составил из скалярных наблюдений N, стандартное отклонение задано как
где μ является средним значением A:
Стандартное отклонение является квадратным корнем из отклонения. Некоторые определения стандартного отклонения используют коэффициент нормализации N вместо N-1, который можно задать установкой w
к 1
.
Расширенные возможности
«Высокие» массивы
Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.
Эта функция поддерживает высокие массивы с ограничением:
-
Схема взвешивания не может быть вектором.
Для получения дополнительной информации смотрите Длинные массивы для Данных, которые не помещаются в память.
Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.
Генерация кода графического процессора
Сгенерируйте код CUDA® для NVIDIA® графические процессоры с помощью GPU Coder™.
Указания и ограничения по применению:
-
Если вы задаете
dim
, затем это должна быть константа.
Основанная на потоке среда
Запустите код в фоновом режиме с помощью MATLAB® backgroundPool
или ускорьте код с Parallel Computing Toolbox™ ThreadPool
.
Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.
Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
Эта функция полностью поддерживает массивы графического процессора. Для получения дополнительной информации смотрите функции MATLAB Запуска на графическом процессоре (Parallel Computing Toolbox).
Распределенные массивы
Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.
Эта функция полностью поддерживает распределенные массивы. Для получения дополнительной информации смотрите функции MATLAB Запуска с Распределенными Массивами (Parallel Computing Toolbox).
Представлено до R2006a