Stefan Falk
Stefan Falk

Reputation: 25457

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.

Upvotes: 2

Views: 726

Answers (1)

damienfrancois
damienfrancois

Reputation: 59260

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}=@(x) x^2
f = 
{
  [1,1] =

@(x) x ^ 2

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

@(x) x ^ 2

  [1,2] =

@(x) x ^ 3

}
>> f{1}(2)
ans =  4
>> f{2}(2)
ans =  8
>> 

Upvotes: 1

Related Questions