Is there a way to pass an anonymous function with an unknown number of variables to a matlab function and perform operations on it?
이전 댓글 표시
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!
채택된 답변
추가 답변 (1개)
Walter Roberson
2013년 12월 18일
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
Andrei Bobrov
2013년 12월 18일
function out = AfuncEval(Afunc, vals)
v = num2cell(vals,2);
vin = cell(size(v));
[vin{:}] = ndgrid(v{:});
out = Afunc(vin{:});
Yakboy287
2013년 12월 19일
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!