1

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.

2
  • What is it that you wish to evaluate?
    – Eitan T
    Mar 10, 2013 at 20:38
  • I need to get out what the f matrix is with x1, x2. Sorry wasn't clear, I'll edit the post Mar 10, 2013 at 20:43

3 Answers 3

1

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])
0
1

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, e.g., b=[2 3] the call f(b) gives [2+3; 2^2+3^2]=[5; 13].

1
  • Matrix subscripts inside brackets is not valid syntax in MATLAB. Also, how does redefining f like this help?
    – Eitan T
    Mar 10, 2013 at 21:58
1

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)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.