1

Is there any way to improve performance with this kind of operation?

t=0:0.01:100;
f=@(t,l) exp(-t.*l)
l=[0.1:0.5:100];
for ll=1:length(l)
    a(ll,:)=f(t,l(ll));
end 

I cannot think of any way to avoid the loop in these cases.

Any help is appreciated .

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Vaaal88
  • 591
  • 1
  • 7
  • 25

3 Answers3

5

How about good ol' matrix multiplication?

a = exp(-l.'*t);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    of course... +1 I wonder whether bsxfun is still faster though. – bla May 23 '14 at 22:23
  • 1
    @Daniel On my computer, for two input vectors of length 3000, this solution is about 4 times faster (0.7s for your solution, 0.175s for this one). – Bentoy13 May 24 '14 at 09:19
  • Can you provide some reference about the use of the combination of symbols A.'*B please? – Vaaal88 May 24 '14 at 13:30
  • 2
    @Vaaal: for `.'` check `doc transpose`, for `*` check `doc mtimes`. – Daniel May 24 '14 at 13:33
4
t=0:0.01:100;
l=[0.1:0.5:100];
b=bsxfun(@(a,b)exp(-a.*b),t,l.')

For the simple case using a row and a column vector, bsxfun evaluates all combinations in a matrix.


Update:

It is possible to increase the speed by a factor of about 4 using bsxfun with times. This is faster because there is a highly optimized implementation for bsxfun for some basic math operations.

t=0:0.01:100;
l=[0.1:0.5:100];
b=exp(bsxfun(@times,-t,l.'))

Third solution, very simple and nearly as fast as my improved or natas solution. Simply preallocate a

t=0:0.01:100;
f=@(t,l) exp(-t.*l)
l=[0.1:0.5:100];
a=nan(numel(l),numel(t));
for ll=1:length(l)
    a(ll,:)=f(t,l(ll));
end 

Matlab should have marked the line a(ll,:)=f(t,l(ll)); with a yellow warning in the editor, it's worth reading them. If you click on it, preallocating is explained.

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • 2
    First, +1 on bsxfun, I always enjoy that people spread the word. Second, a faster preallocation will be `a(numel(l),numel(t))=0;` since prealocation also takes time, you can see how this changes the outcome of the overall performance. See here for a deeper discussion... http://stackoverflow.com/questions/14169222/faster-way-to-initialize-arrays-via-empty-matrix-multiplication-matlab – bla May 23 '14 at 22:19
  • @natan: Never thought it would be possible to improve preallocation using `zeros` or `nan`. I'm reading it, thanks. – Daniel May 23 '14 at 22:33
3

Here's a way using meshgrid:

[t l]=meshgrid(0:0.01:100,0.1:0.5:100);
c=exp(-t.*l);
bla
  • 25,846
  • 10
  • 70
  • 101