arrays of anonymous functions

5 Ansichten (letzte 30 Tage)
john4312
john4312 am 18 Okt. 2016
Kommentiert: Steven Lord am 18 Okt. 2016
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 Kommentar
Steven Lord
Steven Lord am 18 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam
Adam am 18 Okt. 2016
Bearbeitet: Adam am 18 Okt. 2016
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.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by