apply function to each column of a matrix (Vectorizing)

喜欢而已 提交于 2019-12-10 22:05:49

问题


What is fastest way of applying function on each column of a matrix without looping through it?

The function I am using is pwelch but the concept should be the same for any function. Currently I am looping though my matrix as such.

 X = ones(5);
    for i = 1:5 % length of the number of columns
    result = somefunction(X(:,i))
    end

Is there a way to vectorize this code?


回答1:


You say

the concept should be the same for any function

Actually that's not the case. Depending on the function, the code that calls it can be made vectorized or not. It depends on how the function is written internally. From outside the function there's nothing you can do to make it vectorized. Vectorization is done within the function, not from the outside.

If the function is vectorized, you simply call it with a matrix, and the function works on each column. For example, that's what sum does.

In the case of pwelch, you are lucky: according to the documentation (emphasis added),

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.

So pwelch is a vectorized function.



来源:https://stackoverflow.com/questions/29776742/apply-function-to-each-column-of-a-matrix-vectorizing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!