0

I want to splice a list of arguments to pass to a function. For a vector I know that I can use num2cell and call the cell with curly braces (see this question), but in my case the list I want to splice originally has structs and I need to access one of their attributes. For example:

austen = struct('ids', ids, 'matrix', matrix);
% ... more structs defined here

authors = [austen, dickens, melville, twain];

% the function call I want to do is something like
tmp = num2cell(authors);
% myFunction defined using varargin
[a,b] = myFunction(tmp{:}.ids);

The example above does not work because Matlab expected ONE output from the curly braces and it's receiving 4, one for each author. I also tried defining my list of arguments as a cell array in the first place

indexes = {austen.ids, dickens.ids, melville.ids, twain.ids};
[a,b] = myFunction(indexes{:});

but the problem with this is that myFunction is taking the union and intersection of the vectors ids and I get the following error:

Error using vertcat
The following error occurred converting from double to struct:
Conversion to struct from double is not possible.

Error in union>unionR2012a (line 192)
    c = unique([a;b],order);

Error in union (line 89)
    [varargout{1:nlhs}] = unionR2012a(varargin{:});

What is the correct way for doing this? The problem is that I will have tens of authors and I don't want to pass al of them to myFunction by hand.

rodrigolece
  • 1,039
  • 2
  • 13
  • 19
  • Can you give more information on `ids` and `matrix`, so that your code is reproducible? Also, since `authors` is a struct, have you considered using `struct2cell` instead of `num2cell`? – kedarps Jul 18 '17 at 00:43
  • Sorry, `ids` is a (column) vector of integers and `matrix` is a real matrix. Thanks for pointing me in the right direction! `struct2cell` does the trick! – rodrigolece Jul 18 '17 at 16:13
  • great, glad I could help! – kedarps Jul 18 '17 at 16:16

1 Answers1

0

As @kedarps rightly pointed out I need to use struct2cell instead of num2cell. The following code does the trick

tmp = struct2cell(authors);
[a, b] = myFunction(tmp{1,:,:}); %ids is the first entry of the structs

I had never heard about struct2cell before! It doesn't even show up in the See also of help num2cell! It would be amazing to have an apropos function like Julia's....

rodrigolece
  • 1,039
  • 2
  • 13
  • 19