gpt4 book ai didi

matlab - 将函数应用于矩阵的每一列(矢量化)

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:51 24 4
gpt4 key购买 nike

在不遍历矩阵的每一列上应用函数的最快方法是什么?

我正在使用的函数是 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 是一个向量化函数。

关于matlab - 将函数应用于矩阵的每一列(矢量化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com