The problem is that expm
is only implemented for 2D matrices, so you need to call that on 2D slices. The only little bit of possible speed-up is to precalculate xx*A
to a 3D matrix:
n=5;
m=10;
a = rand(1,n);
b = rand(n,1);
A = rand(n,n);
xx = rand(m,1);
tmp = bsxfun(@times,permute(xx,[3 2 1]),A); % Pre-calculate the matrix multiplication
fxx = zeros(m,1);
for ii = 1:m
fxx(ii) = a*expm(tmp(:,:,m))*b;
end
although I doubt it'll save you a lot of time this way. The main speed-up compared to your code, would be to preallocate fxx
, as I have done, since that saves MATLAB from allocating and deallocating your array each loop iteration.
In your comments you state that m
is generally very large. If that is the case, parfor
might help you if you have the parallel computation toolbox. In that case, pre-calculating the 3D matrix might not work, since it'll be very large in RAM, so simply use:
fxx=zeros(m,1);
parfor ii = 1:m
fxx(ii) = a*expm(xx(ii)*A)*b;
end
For more information on how parfor
can help you, and how it can be even faster when slicing your variables properly, see the following question: Saving time and memory using parfor?