Reputation: 13
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.
Upvotes: 1
Views: 5153
Reputation: 32930
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)]
Upvotes: 1
Reputation: 13610
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]
.
Upvotes: 1
Reputation: 2201
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])
Upvotes: 1