Solve X: you want to add the values for a function for all P, C, lambda values. Attempt with using function handles, called Solution Y.
Solve Y: you make a lot of function handles for all P, C, lambda sets. But this is too slow. You want a solution to make Solution Y faster, not seeing a faster solution for X.
C = rand(1000, 1);
P = rand(1000, 1);
lambda = rand(1000, 1);
t = 1:10000;
Ysum = zeros(1, length(t));
for i = 1:length(C)
fh = @(t) P(i)*exp(-lambda(i)*t) + C(i);
Ysum = Ysum + fh(t);
end
t2 = toc
tic
Ysum = sum(bsxfun(@times, exp(-lambda*t), P) + C, 1);
t1 = toc
I notice you like using repmat and find. Note that use of repmat is slower than bsxfun. Also, if possible, avoid using find if dealing with logical indexing. For instance:
function uh_fun=expconv(lambda)
k=length(lambda);
temp_den = lambda' - lambda;
ind = temp_den == 0;
if sum(ind(:)) > k
error('atleast two of the pdfs to be convolved are identical')
else
temp_den(ind) = 1;
den=prod(temp_den);
nume=prod(lambda);
C=nume./den;
for i=1:k
uh_fun{i}=@(t)exp(-lambda(i)*t)*C(i);
end
end
end
If this is still too slow, then you could try using parfor or mex functions.
Best Answer