snar
snar

Reputation: 145

Function handle applied to array in MATLAB

I've searched and there are many answers to this kind of question, suggesting functions like arrayfun, bsxfun, and so on. I haven't been able to resolve the issue due to dimension mismatches (and probably a fundamental misunderstanding as to how MATLAB treats anonymous function handles).

I have a generic function handle of more than one variable:

f = @(x,y) (some function of x, y)

Heuristically, I would like to define a new function handle like

g = @(x) sum(f(x,1:3))

More precisely, the following does exactly what I need, but is tedious to write out for larger arrays (say, 1:10 instead of 1:3):

g = @(x) f(x,1)+f(x,2)+f(x,3)

I tried something like

g = @(x) sum(arrayfun(@(y) f(x,y), 1:3))

but this does not work as soon as the size of x exceeds 1x1.

Thanks in advance.

Upvotes: 0

Views: 444

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

Assuming you cannot change the definition of f to be more vector-friendly, you can use your last solution by specifying a non-uniform output and converting the output cell array to a matrix:

g = @(x) sum(cell2mat(arrayfun(@(y) f(x,y), 1:3,'UniformOutput',false)),2);

This should work well if f(x,y) outputs column vectors and you wish to sum them together. For rows vectors, you can use

g = @(x) sum(cell2mat(arrayfun(@(y) f(x,y), 1:3,'UniformOutput',false).'));

If the arrays are higher in dimension, I actually think a function accumulator would be quicker and easier. For example, consider the (extremely simple) function:

function acc = accumfun(f,y)
    acc = f(y(1));
    for k = 2:numel(y)
        acc = acc + f(y(k));
    end
end

Then, you can make the one-liner

g = @(x) accumfun(@(y) f(x,y),y);

Upvotes: 2

Related Questions