【问题标题】:Splice list of structs into arguments for function call - Matlab将结构列表拼接成函数调用的参数 - Matlab
【发布时间】:2017-07-18 00:35:57
【问题描述】:

我想拼接一个参数列表以传递给一个函数。对于一个向量,我知道我可以使用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 期望从花括号输出 ONE 并且它接收 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

【问题讨论】:

  • 您能否提供更多有关idsmatrix 的信息,以便您的代码可重现?另外,由于authors 是一个结构,你有没有考虑过使用struct2cell 而不是num2cell
  • 抱歉,ids 是整数(列)向量,matrix 是实数矩阵。感谢您为我指明正确的方向! struct2cell 成功了!
  • 太好了,很高兴我能帮上忙!

标签: matlab


【解决方案1】:

正如@kedarps 正确指出的那样,我需要使用struct2cell 而不是num2cell。以下代码可以解决问题

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多