arrays of anonymous functions

5 vues (au cours des 30 derniers jours)
john4312
john4312 le 18 Oct 2016
Commenté : Steven Lord le 18 Oct 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 commentaire
Steven Lord
Steven Lord le 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.

Connectez-vous pour commenter.

Réponse acceptée

Adam
Adam le 18 Oct 2016
Modifié(e) : Adam le 18 Oct 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.
  1 commentaire
john4312
john4312 le 18 Oct 2016
thank dude ! I miss that

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by