arrays of anonymous functions
5 ビュー (過去 30 日間)
古いコメントを表示
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
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.
採用された回答
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!