1

i need your help in solving the following problem:

how can i generalize the following for any n dimensional array:

reshape(arrayfun(@(x,y)sprintf('%d,%d',x,y),C{:},'un',0),size(M));

M is my matrix and C is my matrix of indexes of M.

thanks in advance.

2 Answers2

0

The problem isn't the number of dimensions in the arguments to arrayfun per se, but the number of arguments themselves - which happens in your example to correspond to the number of dimensions each argument has. You therefore need to pass it a function that accepts varargin, which still works on an anonymous function:

reshape(arrayfun(@(varargin)sprintf(strjoin(repmat('%d',size(varargin)),','),varargin{:}),C{:},'un',0),size(M));
Will
  • 1,835
  • 10
  • 21
  • what i need to pass as varargin ? – terez tukan Oct 30 '15 at 19:21
  • `varargin` is the list of input arguments to the anonymous function that is the first argument to `arrayfun`. The arguments that are passed to that anonymous function are the next arguments to `arrayfun`, i.e. the arrays contained in each cell of `C`. That's how your original example works too, just with a fixed number (2) of elements in `C` required to be able to pass as arguments to the anonymous function. – Will Oct 30 '15 at 20:27
0

This function gave me a lot of headache.

For functions like

f1 = @(x1,x2) x1*x2

You can do

output = arrayfun(f1,x1,x2);

where x1 and x2 are input columns.

However, if you're doing a generalized program, where f1 could have any number of inputs and you need a generalized input matrix like X, you'll need, for example

f1 = @(x1,x2,x3,x4,x5) 2*x1+4*x2+10*x3+0.2*x4+x5;

output = arrayfun(f1,num2cell(X,1){:});

where X represents a matrix with 5 columns representing x1 through x5 For example:

X = [1, 2, 3, 4, 5;
     6, 7, 8, 9, 0;];
DanBC
  • 145
  • 2
  • 10