MATLAB: Arrays of anonymous functions

anonymous functioncell arraysempty array

I want to create an array of anonymous functions in a loop , but all my arrays are becoming empty except for the last one . Please Help ! I have used J =50 ! . Note : If I display the function after each loop evaluation , it works !
function[g]=poly1(J)
xa=-1;xb=1;
dx=(xb-xa)/J;
x=xa:dx:xb;
for i=1:J+1
g=cell(J+1,1);
a=x(i);
a1=a+dx/2;a2=a-dx/2;
a3=[a1,a,a2];
ux=-sin(pi*a3);
y=polyfit(a3,ux,2);
a=y(1);b=y(2);c=y(3);
g{i}=eval(sprintf('@(x) %d*x^2+%d*x+%d',a,b,c));
end

Best Answer

g=cell(J+1,1);
in the first line of your for loop overwrites everything previously in g. Move it outside the for loop instead.