Estimate multivariate function with varying input dimension

For the function f: R ^ m → R ^ n, where m, n change all the time. What would be the best way to implement this in the Matlab function, which evaluates the output at an arbitrary point x∈R ^ m.

The fact that the function is a vector estimate, i.e. its target space is multidimensional, it is easy to take care of using an array of anonymous functions. Then we can use a simple loop:

function testFunc(f,x)
resultArray = zeros(numel(f),1);
for kk = 1: length(f)
    resultArray(kk) = f{kk}(x);
end
resultArray
end

In the case m = 1, n = 3 with the following function

f = {@(x) (x*x); @(y) (exp(y)); @(z) (cos(z))}

gives the expected output

testFunc(f,2)

resultArray =

4.000000000000000
7.389056098930650
-0.416146836547142

If m needs to be fixed, this could easily be extended to the case of multiple variables. But I do not know the value of m in advance.

How to solve this problem? Thanks in advance.


Example. Let's say that I have successfully implemented my testFunc function. Then the command line should look something like this:

 >> f = @(x,y) (x*y);
 >> g = @(x,y,z) (exp(x*y*z));
 >> h = {@(x,y) (log(x*y)); @(x,y) (sin(x*y))}
 >> p = [1;2];
 >> q = [1;2;3];
 >> testFunc(f,p)
 ans = 
       2
 >>testFunc(g,q)
 ans =

       4.034287934927351e+02
 >> testFunc(h,p)
 ans =
       0.693147180559945 
       0.909297426825682
+4
1

, , . , . . , .

function testFunc(f,x)

    x=num2cell(x);

    resultArray = zeros(numel(f),1);

    if ~iscell(f)
        f={f};
    end

    for kk = 1: length(f)
       resultArray(kk) = f{kk}(x{:});
    end

    resultArray

end
0

Source: https://habr.com/ru/post/1584906/


All Articles