scale()R函数等效于Octave/Matlab [英] scale() R function equivalent in Octave/Matlab
问题描述
避免循环,是否有一种方法可以使数据矩阵围绕列(或行)的平均值居中,并按标准偏差(按列或按行)缩放每个条目?
Avoiding loops, is there a way to center a matrix of data around the mean of the columns (or rows), scaling each entry by the standard deviation (also column-wise or row-wise)?
在R中,这很容易:scale(data, center = T, scale = T))
.
但是我不知道如何在Ocatave或Matlab中实现相同的基本预处理.
But I don't know how to achieve the same basic pre-processing in Ocatave or Matlab.
推荐答案
没有单个函数可以执行此操作,但是您可以对std
和mean
使用dim
参数来完成此操作.我们还可以使用bsxfun
将它们全部包装成一行.
There isn't a single function that does this but you can use the dim
parameter for std
and mean
to accomplish this. We can also use bsxfun
to wrap it all into one line.
A = rand(5, 4);
% Column-wise
bsxfun(@rdivide, bsxfun(@minus, A, mean(A, 1)), std(A, [], 1))
% Row-wise
bsxfun(@rdivide, bsxfun(@minus, A, mean(A, 2)), std(A, [], 2))
说明
使用mean
的dim
参数,我们可以计算A
每一列的平均值.
Using the dim
parameter to mean
we can compute the mean value for each column of A
.
M = mean(A, 1)
然后,我们可以使用bsxfun
从每列(@minus
)中的每个值中减去平均值.我们需要使用bsxfun
,因为M
是1 x nCols
,而A
是nRows x nCols
. bsxfun
将自动为我们广播操作.
Then we can use bsxfun
to subtract the mean from each value in each column (@minus
). We need to use bsxfun
because M
is 1 x nCols
and A
is nRows x nCols
. bsxfun
will automatically broadcast the operation for us.
B = bsxfun(@minus, A, M);
然后,我们要再次使用dim
参数(第三输入)来计算每列的标准偏差.
Then we want to compute the standard deviation of each column, again using the dim
parameter (third input).
S = std(A, [], 1)
然后将每列除以该标准差
And divide each column by this standard deviation
bsxfun(@rdivide, B, S);
因此,我们将所有这些整合在一起
So bringing this all together we get
bsxfun(@rdivide, bsxfun(@minus, A, mean(A, 1)), std(A, [], 1))
要执行按行操作,我们要做的就是将dim
参数从1(列)切换为2(行).
To perform the row-wise operation, all we need to do is switch the dim
parameter from 1 (columns) to 2 (rows).
这篇关于scale()R函数等效于Octave/Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!