Apply a function to each column of a matrix (vectorization)

What's the fastest way to apply a function to each column of a matrix without scrolling through it?

The function I am using pwelch

, but the concept should be the same for any function. I am currently looping though my matrix is ​​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?

+3


source to share


1 answer


You speak

the concept should be the same for any function

Actually, it is not so. Depending on the function, the code that calls it can be vectorized or not. It depends on how the function is written internally. From the outside of the function, there is nothing you can do to make it vectorized. Vectorization is done inside the function, not outside.

If the function is vectorized, you just call it using the matrix and the function works on every column. For example, what it does sum

.



In case pwelch

you're in luck: according to the documentation (emphasis mine),

Pxx = pwelch(X)

returns the estimated power spectral density (PSD),, Pxx

...

When X

is a matrix, PSD is computed independently for each column and stored in the corresponding column Pxx

.

So pwelch

is a vector function.

+3


source







All Articles