arrays of anonymous functions
6 views (last 30 days)
Show older comments
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
1 Comment
Steven Lord
on 18 Oct 2016
There is no need to use eval here.
a = 1;
b = 2;
c = 3;
g{1} = @(x) a*x.^2+b*x+c;
I know what you're likely to say -- g doesn't show the values of the coefficients, just the variables. The values of those coefficients are stored in the anonymous function and are used when it is evaluated. And if your coefficients are not exactly integer values, the difference could be important.
a = exp(1);
g{1} = @(x) x+a;
g{2} = eval(sprintf('@(x) x+%d', a));
g{1}(0)-a % should be 0 and is 0.
g{2}(0)-a % should be 0 but isn't 0.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!