27 views (last 30 days)

Hi all,

I'm trying to generate an anonymous function where I pass in an array of structures and convert it to a structure of arrays (possibly offsetting the indices for each of the inputs). I've been doing it so far using an anonymous function, but I'm trying to figure out how to generalize it.

Here's what I've got so far:

Sync = @(x,fna) [x(1).(fna)(shape_params.indices{1}),...

x(2).(fna)(shape_params.indices{2})];

So when I call it I give it the array of structures (x), and the field name (fna) that I want to create the output array of. shape_param.indices is a cell array that tells me which entries I want from each of the entries in the array of structs.

For example:

XX(1).a = (1:10)';

XX(2).a = (2:11)';

shape_params.indices{1} = (2:5)';

shape_params.indices{2} = (1:4)';

YY.a = Sync(XX,'a')

should give me:

YY.a = [2,2;3,3;4,4;5,5];

I can define Sync to accomodate the number of entries in XX by just creating a switch. But now I need to generalize it, since I don't want to make a switch statement that has up to 16 varieties.

Any suggestions on how I can do it, for an unknown number of vectors that I'm combining?

Thanks, Dan

Cedric Wannaz
on 7 Feb 2013

It is difficult to implement conditional statements in anonymous functions (it requires a test function); why do you want to use an anonymous function? Couldn't you simply do something like the following?

data = [XX(:).a] ; idx = [shape_params.indices{:}] ;

YY.a = cell2mat(arrayfun(@(c)data(idx(:,c),c), 1:size(data,2), ...

'UniformOutput', false)) ;

Cedric Wannaz
on 7 Feb 2013

Sign in to comment.

Tucker McClure
on 8 Feb 2013

Not sure I exactly understand you, Dan, but is this what you're trying to do? This is the anonymous function version. You might want to consider making a private method instead, but if it needs to be anonymous, then this seems to get the job done.

f = @(objects, indices) ... % Function header

arrayfun(@(k) objects(k).field(indices{k}), ... % Get indices of obj(k)

1:length(objects), ... % for k = 1:n.

'UniformOutput', false); % Output in cells.

my_struct_array(1).field = (1:10)';

my_struct_array(2).field = (2:2:20)';

my_indices = {1:5, 6:10};

f(my_struct_array, my_indices)

Also, if the indices are guaranteed to be the same length, then you could output to a matrix instead of a cell array by adding a cell2mat(...) around the arrayfun(...).

Hope that helps.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/62634-how-to-make-an-anonymous-function-for-variable-amount-of-input-data#comment_127909

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/62634-how-to-make-an-anonymous-function-for-variable-amount-of-input-data#comment_127909

Sign in to comment.