1

Is it possible to pass the sum function and declare how to summarize the values? So column or row wise? Like I call the function without passing:

y = sum(x,2);

I want to call an Aggregation function like this, but operate in the rows:

Output = Aggregate(Input,@sum);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147

2 Answers2

2

To apply the passed function along the second dimension:

Aggregate = @(x,fun) fun(x,2);

As you see, this calls the passed function (fun) on the input (x) , with a fixed extra argument 2 to indicate the dimension along which the function will operate. This will work for any function that, like sum, accepts the dimension as a second argument.

Examples:

>> Aggregate([1 2; 3 4], @sum)
ans =
     3
     7
>> Aggregate([1 2; 3 4], @prod)
ans =
     2
    12

To apply the passed function along a specified dimension:

Aggregate = @(x,fun,dim) fun(x,dim);

Example:

>> Aggregate([1 2; 3 4], @sum, 2)
ans =
     3
     7
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • In the aggregate function, I do a lot of other calculations, and I want to pass the sum function as an input parameter, which I want to use in the aggregate function. The Aggregate function itself should not be the function to sum up my values. – Iulius Caesar Nov 04 '15 at 06:27
  • Well, that's exactly what my code does, isn't it? See my examples above with the `sum` and `prod` functions passed as inputs – Luis Mendo Nov 04 '15 at 11:06
  • I understand your code in the way, that you define the `Aggregate` function in the Workspace and the `Aggregate` function does calculations with values and a function like `sum` or `prod`. But my Intention is to pass an input parameter (in my case `sum` function) to another function, which is defined in another script. In a part of the other function I want to use the input Parameter, the `sum` function, to make some calculations. The Aggregate function itself should not only return the sum or product of my given array. Therefore, solution `output = Aggregate(Input,@(x)sum(x,2)` works for me. – Iulius Caesar Nov 04 '15 at 12:11
1

Depends a little on how Aggregate uses the function handle it's being passed, but the following should work

Output = Aggregate(Input,@(x)sum(x,2));

Phil Goddard
  • 10,571
  • 1
  • 16
  • 28