Reputation: 328
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?
Upvotes: 3
Views: 993
Reputation: 112769
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 ofPxx
.
So pwelch
is a vectorized function.
Upvotes: 3