当前位置: 动力学知识库 > 问答 > 编程问答 >

Matlab: Array of inline functions. Call single function

问题描述:

I got this array of inline functions that I defined:

x = 0:1/(nDatasets-1):1;

M = 24; % number of base functions

f = cell(M,1);

for m = 1:M

f{m} = inline(sprintf('exp(- (x- %d/(%d+1)).^2/(1/(2*%d^2)))', m,M,M), 'x');

end

But I have no idea how I can now access/call a single function.

网友答案:

Simply with f{index}(arguments). Example:

>> f{1}=inline(sprintf("x^2"))
f = 
{
  [1,1] = f(x) = x^2
}
>> f{2}=inline(sprintf("x^3"))
f = 
{
  [1,1] = f(x) = x^2
  [1,2] = f(x) = x^3
}
>> f{1}(2)
ans =  4
>> f{2}(2)
ans =  8

Alternatively, you can assign the inline function to a temporary variable and then use it like a normal function:

>> tmpf=f{1}
tmpf = f(x) = x^2
>> tmpf(2)
ans =  4

Note that this also works with anonymous functions:

>> f{1}[email protected](x) x^2
f = 
{
  [1,1] =

@(x) x ^ 2

}
>> f{2}[email protected](x) x^3
f = 
{
  [1,1] =

@(x) x ^ 2

  [1,2] =

@(x) x ^ 3

}
>> f{1}(2)
ans =  4
>> f{2}(2)
ans =  8
>> 
分享给朋友:
您可能感兴趣的文章:
随机阅读: