简体   繁体   中英

Passing matrix to function handle (MATLAB)

If I have a set of functions

f = @(x1,x2) ([x1 + x2; x1^2 + x2^2])

and I have a second matrix with

b = [x1,x2]

How do I evaluate f([b]) ? The only way I know how is to say f(b(1),b(2)) but I can't figure out how to automate that because the amount of variables could be up to n. I'm also wondering if there is a better way than going individually and plugging those in.

You could rewrite your functions to take a vector as an input.

f = @(b)[b(1) + b(2); b(1)^2 + b(2)^2]

Then with, eg, b=[2 3] the call f(b) gives [2+3; 2^2+3^2]=[5; 13] [2+3; 2^2+3^2]=[5; 13] [2+3; 2^2+3^2]=[5; 13] .

convertToAcceptArray.m:

function f = convertToAcceptArray(old_f)
    function r = new_f(X)
        X = num2cell(X);
        r = old_f(X{:});
    end
    f = @new_f
end

usage.m:

f = @(x1,x2) ([x1 + x2; x1^2 + x2^2])
f2 = convertToAcceptArray(f);
f2([1 5])

Assuming that b is an N-by-2 matrix, you can invoke f for every pair of values in b as follows:

cell2mat(arrayfun(f, b(:, 1), b(:, 2), 'UniformOutput', 0)')'

The result would also be an N-by-2 matrix.

Alternatively, if you are allowed to modify f , you can redefine it to accept a vector as input so that you can obtain the entire result by simply calling f(b) :

f = @(x)[sum(x, 2), sum(x .^ 2, 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM