MATLAB: An Efficient Way to Run a Vector Input Function Using Array Input
I have a function HermitePCECoefficients
that takes several parameters as input, including a column vector y
, and outputs a column vector Coefficients
, the same length as y
:
Coefficients=HermitePCECoefficients(grid,weights,indices,y,mu,sigma,normalized)
Suppose now that is y
not a column vector but is a two dimensional array (matrix) and I want to run HermitePCECoefficients
in each of my columns while storing the corresponding outputs in the array. Doing this with a loop for
is simple and straightforward, but it takes forever:
Coefficients=zeros(size(y));
for i=1:size(y,2)
Coefficients(:,i)=HermitePCECoefficients(grid,weights,indices,y(:,i),mu,sigma,normalized);
end
So I put it bsxfun
on the job. Since bsxfun
it only works with binary functions, I created a binary function "dummy" f, which is actually only a function of one argument:
f=@(a,b) HermitePCECoefficients(grid,weights,indices,a,mu,sigma,normalized);
Then used bsxfun
like this:
Coefficients=bsxfun(f,y,omega_f);
This works great and is much faster than a loop for
(don't worry omega_f
, it's just a vector whose length matches the number of columns in y
).
Question 1: What do you think is the correct way to use bsxfun
in this context?
Question 2: Perhaps the best solution would be to modify directly HermitePCECoefficients
so that it can accept a shared array y
as input. Inside the function, this is the only line that requires it to y
be a column vector:
Coefficients(i)=dot(weights,y.*Psi)/norm;
weights
and Psi
are two column vectors, so if I pass an array y
MATLAB complains. Any suggestions for changing it? Thank,
Sergio
source to share
Option 2 seems to be better (but only testing will be tested). Just replace
dot(weights,y.*Psi)/norm
by
sum(bsxfun(@times, weights.*Psi, y)/norm)
or (possibly faster)
(weights.*Psi).'*y / norm
Any of the above is equivalent to computing a vector [ dot(weights,y(:,1).*Psi)/norm, dot(weights,y(:,2).*Psi)/norm, ... ]
for an arbitrary number of columns y
. Each entry in this vector is the result for a column y
.
source to share