Question: I'm using a Matlab program that has a very long loop, inside this loop is the following code: 

```
...  
H = fspecial('gaussian', 6*sig(i), sig(i));
img_out = imfilter(img{i},H,'same');
...

```

Where 'sig' is a list of Gaussian widths, and 'img' is a cell array of images.

I need to make this code more efficient and perhaps those two points will allow for something more clever:

1. The filter is always Gaussian - just different sigma.
2. The image inside 'img{i}' is a grayscale **sparse** matrix.

Answer: 
I found a wonderful solution to the problem:
<http://blog.ivank.net/fastest-gaussian-blur.html>

There is a quick implementation in Matlab Help files:

```
intImage = integralImage(I);
avgH = integralKernel([1 1 7 7], 1/49);
J = integralFilter(intImage, avgH);

```

So 3 passes of that should approximate a Gaussian!
I tried to batch process images of same size and sigma, stacking them:

```
%problem generator
%real number is 10^6
num_of_images=10^4;
%i assume squared images
image_size=randi([60,100],num_of_images,1);
sig=randi([2,4],num_of_images,1);
img=cell(num_of_images,1);
ratio_nnz=.02;
for idx=1:num_of_images
    ti=rand(image_size(idx))/ratio_nnz;
    ti(ti>1)=0;
    img{idx}=ti;
end
%existing approac
tic;
for idx=1:num_of_images
H = fspecial('gaussian', 6*sig(idx), sig(idx));
img_out = imfilter(img{idx},H,'same');
end
toc;
%idea: Match images of same sigma and 
tic
%calculate all filters offline
[sig_unique,~,sig_index]=unique(sig);
H=cell(numel(sig_unique),1);
for idx=1:numel(sig_unique)
   H{idx}= fspecial('gaussian', 6*sig_unique(idx), sig_unique(idx));
end
%find instances of same size and sigma
[x,y]=cellfun(@size,img);
[a,b,c]=unique([sig_index,x,y],'rows');
img_out=cell(size(img));
for didx=1:numel(b)
    %img{c==didx} contains images of same sigma and size, process them at
    %once
    iH=H{a(didx,1)};
    timg=cat(3,img{c==didx});
    timg_out=imfilter(timg,iH,'same');
    img_out(c==didx)=num2cell(timg_out,[1,2]);
end
toc

```

The result surprised me, actually calling `imfilter` with less but larger matrices was slower with the data I generated. Nevertheless try it with your data and or the faster gaussian filter you are planning to implement. It might be faster then.