Apply own function to each element without loops in Matlab -


i trouble. have matrices

f=magic(5) h=magic(5) g=magic(5) 

wand them need following algorithm:

for x=1:size(f,1)   y=1:size(f,2)      fp=f;      fp(x,y)=fp(x,y)+a;      q(x,y)=sum(sum(conv2(fp,h,'same')-g));   end end 

how can avoid nested loops? thought arrayfun, no idea apply in case.

what's wrong loop? if you're worried performance, , real arrays larger in example, may want @ replacing convolution fourier transform.

to make easier matlab optimize loop, can replace double loop single loop:

q = zeros(size(f)); %# preallocation important idx=1:numel(f)      fp=f;      fp(idx)=fp(idx)+a;      q(idx)=sum(sum(conv2(fp,h,'same')-g));   end end 

if want solution arrayfun, can use indicator function adding a right element. note becomes lot harder read (and therefore maintain) loop solution.

idxmat = reshape(1:numel(f),size(f)); q = arrayfun(@(x)sum(sum(conv2(f+double(idxmat==x)*a,h,'same')-g)), idxmat); 

Comments