将函数应用于矩阵的每一列(矢量化)
apply function to each column of a matrix (Vectorizing)
在不遍历矩阵的每一列上应用函数的最快方法是什么?
我使用的函数是pwelch
,但任何函数的概念应该是相同的。
目前我正在循环遍历我的矩阵。
X = ones(5);
for i = 1:5 % length of the number of columns
result = somefunction(X(:,i))
end
有没有办法向量化此代码?
你说
the concept should be the same for any function
其实不然。根据函数的不同,调用它的代码可以矢量化或不矢量化。这取决于函数内部是如何编写的。从函数外部,您无法对其进行矢量化。矢量化是在函数内完成的,而不是从外部完成的。
如果函数 是 向量化的,您只需使用矩阵调用它,该函数就会作用于每一列。例如,这就是 sum
所做的。
在pwelch
的情况下,你很幸运:根据documentation(强调已添加),
Pxx = pwelch(X)
returns the Power Spectral Density (PSD) estimate, Pxx
, ...
When X
is a matrix, the PSD is
computed independently for each column and stored in the corresponding
column of Pxx
.
所以pwelch
是一个向量化函数。
在不遍历矩阵的每一列上应用函数的最快方法是什么?
我使用的函数是pwelch
,但任何函数的概念应该是相同的。
目前我正在循环遍历我的矩阵。
X = ones(5);
for i = 1:5 % length of the number of columns
result = somefunction(X(:,i))
end
有没有办法向量化此代码?
你说
the concept should be the same for any function
其实不然。根据函数的不同,调用它的代码可以矢量化或不矢量化。这取决于函数内部是如何编写的。从函数外部,您无法对其进行矢量化。矢量化是在函数内完成的,而不是从外部完成的。
如果函数 是 向量化的,您只需使用矩阵调用它,该函数就会作用于每一列。例如,这就是 sum
所做的。
在pwelch
的情况下,你很幸运:根据documentation(强调已添加),
Pxx = pwelch(X)
returns the Power Spectral Density (PSD) estimate,Pxx
, ...When
X
is a matrix, the PSD is computed independently for each column and stored in the corresponding column ofPxx
.
所以pwelch
是一个向量化函数。