One possible option would be to use a cell array of function handles, since funcell{k1,k2}(3)
is valid syntax. However, using cells would also be pretty slow.
So I suggest transforming your whole symbolic array of functions to an array-valued symbolic array, and working on that. So, with your example:
syms x;
T_m = [[exp(x), x^2];[x,sin(x)]];
funT = matlabFunction(T_m);
%// produces @(x)reshape([exp(x),x,x.^2,sin(x)],[2,2])
You can use the sum of this quantity as a new anonymous function,
main_func = @(x) sum(sum(funT(x)));
which might be the same thing that Troy Haskin suggested.
The main reason I decided to add an answer is to also address your other, related question. If you want to use the individual elements of the original array of functions, you should either use a cell array of handles after all (then you just have to access funcell{k1,k2}(x)
), or if it turns out that using cells is slower than unnecessarily computing the full array, just throw away what you don't need:
id1 = eye(size(T_m,1))); %// for Kronecker delta, essentially
id2 = eye(size(T_m,2))); %// same here
T_m12 = @(x) id1(1,:)*funT(x)*id2(:,2);
%// or even better, generally
funT_m = @(x,k1,k2) id1(k1,:)*funT(x)*id2(:,k2);
To complete the circle: if you start from a cell array of function handles, you can transform that to an array-valued function handle, which is really ugly and messy, but should work unless your function is a very huge beast (but in that case, all hope's lost anyway).
Final note, just for the sake of completeness: the answer to the suggested duplicate of your other question shows you how you can assign into the return value of a function call, without using a temporary variable. The main problem with this approach is that it makes the code impossible to read by human beings, but otherwise it is as low-level as it gets in terms of efficiency. If you're desperate, you might consider this route as well (as it doesn't involve cells, symbolic math, nor an unnecessary vector-matrix-vector product):
funT_m = @(x,k1,k2) subsref(funT(x),struct('type','()','subs',{{k1,k2}}));
But bear in mind that we're still computing the full array in x
, we're just throwing away the unnecessary parts as efficiently as possible.
Post-final note: if you eventually want to integrate every matrix element you have, you should also consider using the full array-valued function in integral
, making use of its 'arrayvalued',true
parameter-value pair. This will make the integration become slower, but you can compute the integral of every matrix element all at once, without having to throw away any results.