MATLAB: Can this function work any faster

faster codeimage processingImage Processing Toolbox

Hello All, Well I'm making a function that takes about 0.022 seconds to complete, I need to try to make it even less time then that, just getting peoples opinions. The end result needs to run at 120 Hz, I have tried most matlab built in functions, but there too slow for what I need, I know because I've tried. This is designed to be used for an accelerator beam image, it is just a "spot" on the screen and the image coming in has about 606×1182 pixels in it. The inputs are an image and a threshold(which is usually == 0). I pretty much have striped down to bare essentials for this code, however hope there was something I missed that will make it faster. I was just hoping for peoples comments or options about any way to make this code faster(or if there is a better way):
function [clipedImg,tfr,tfc] = ImageClipper(useImg,threshold)
useImg = double(useImg); %????????????????????????
mx = max(useImg);
my = max(useImg,[],2);
sorted=sort(my(:));
dist=diff([sorted; sorted(end)-1]);
idx=find(dist);
num=[idx(1); diff(idx)];
n=max(num);
ty=sorted(idx(num==n));
v = mx > ty;
na = length(v);
b = [1 -1];
[k,zf] = filter(b, 1, v);
k(na+1:na+2-1) = zf;
P = find(k==1);
L = find(k==-1)-P;
LP = [max(L) P(L==max(L))];
tfc = [false(1,LP(1,2)-threshold) true(1,LP(1,1)+2*threshold) false(1,length(mx)-sum(LP)-threshold)];
v = my > ty;
na = length(v);
b = [1 -1];
[k,zf] = filter(b, 1, v);
k(na+1:na+2-1) = zf;
P = find(k==1);
L = find(k==-1)-P;
LP = [max(L) P(L==max(L))];
tfr = [false(1,LP(1,2)-threshold) true(1,LP(1,1)+2*threshold) false(1,length(my)-sum(LP)-threshold)];
clipedImg = useImg(tfr,tfc);
Thanks!

Best Answer

Another husky!
You could avoid the max operation here as well:
[L posP]= max(find(k==-1)-P);
Instead:
find(k==-1,1,'last')-P
Now it only needs to find the first occurence of a -1 and not all of them allowing it to stop prematurely.
Avoid operations like the following that change the size or class of an array:
P = P(posP);
Also, to address DPB's point: do you have MATLAB Coder? If so, you could try generating code from this and then compiling it into a MEX file that might run faster.