Is there a way to pass an anonymous function with an unknown number of variables to a matlab function and perform operations on it?
Afficher commentaires plus anciens
Basically what I want to do is take in an anonymous function like:
Afunc = @(a,b,c,...) a+b+c+...; % for any number of variables
and pass it and values for each variable (say in an n-dimensional matrix where n is the number of variables in Afunc) into a matlab function that will evaluate it at all points. So:
Amatrix = AfuncEval(Afunc,vals);
An example using 3 variables:
Afunc = @(a,b,c) a+b+c;
vals = [[1 2 3];[4 5 6];[7 8 9]]; % vals(1,:) are values for variable a, vals(2,:) are b, etc.
Amatrix = AfuncEval(Afunc,vals);
Amatrix(1,1,1) = Afunc(1,4,7);
Amatrix(1,1,2) = Afunc(1,4,8);
And so on. I've looked all over and haven't managed to find a completely general approach to anonymous functions. The closest I've come is using a cell function:
cellfun(Afunc,val{:});
but this only evaluates Afunc at (1,4,7), (2,5,8), and (3,6,9). I could set up val so that it evaluates Afunc at all combinations of the variable values, but that would still require knowing how many variables there are ahead of time. Has anyone tried to do anything like this before?
Thanks very much!
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 18 Déc 2013
function r = AfuncEval(Afunc, vals)
nvars = size(vals,1);
vals_cell = mat2cell(vals, ones(nvars,1), size(vals,2));
vals_grids = cell(nvars,1);
[vals_grids{:}] = ndgrid(vals_cell{:});
r = Afunc(vals_grids{:});
end
2 commentaires
Andrei Bobrov
le 18 Déc 2013
function out = AfuncEval(Afunc, vals)
v = num2cell(vals,2);
vin = cell(size(v));
[vin{:}] = ndgrid(v{:});
out = Afunc(vin{:});
Yakboy287
le 19 Déc 2013
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!