我想拼接一个要传递给函数的参数列表。对于向量,我知道我可以使用num2cell并调用带大括号的单元格(参见this question),但在我的例子中,我想拼接的列表最初具有structs,并且我需要访问它们的一个属性。例如:
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。
发布于 2017-07-19 00:11:53
正如@kedarps正确指出的那样,我需要使用struct2cell而不是num2cell。下面的代码做到了这一点
tmp = struct2cell(authors);
[a, b] = myFunction(tmp{1,:,:}); %ids is the first entry of the structs我以前从未听说过struct2cell!它甚至不会出现在help num2cell的See中!如果有一个apropos函数like Julia's,那就太棒了……
https://stackoverflow.com/questions/45155651
复制相似问题