arrays of anonymous functions

5 ビュー (過去 30 日間)
john4312
john4312 2016 年 10 月 18 日
コメント済み: Steven Lord 2016 年 10 月 18 日
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 件のコメント
Steven Lord
Steven Lord 2016 年 10 月 18 日
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.

サインインしてコメントする。

採用された回答

Adam
Adam 2016 年 10 月 18 日
編集済み: Adam 2016 年 10 月 18 日
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 件のコメント
john4312
john4312 2016 年 10 月 18 日
thank dude ! I miss that

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by