将结构列表拼接成函数调用的参数 - Matlab

时间:2017-07-18 00:35:58

标签: matlab

我想拼接一个参数列表以传递给一个函数。对于向量,我知道我可以使用num2cell并使用大括号调用单元格(请参阅this question),但在我的情况下,我想要拼接的列表最初有struct s和我需要访问其中一个属性。例如:

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);

上面的示例不起作用,因为Matlab期望花括号中的一个输出并且它接收4,每个作者一个。我还尝试将我的参数列表首先定义为单元格数组

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

但是问题是myFunction正在采用向量ids的并集和交集,我得到以下错误:

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{:});

这样做的正确方法是什么?问题是我将有数十位作者,而且我不想手动将它们传递给myFunction

1 个答案:

答案 0 :(得分:0)

正如@kedarps正确地指出我需要使用struct2cell而不是num2cell。以下代码可以解决这个问题

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

我之前从未听说过struct2cell!它甚至没有出现在help num2cell的另见中!拥有apropos函数like Julia's ....

会很棒
相关问题