【问题标题】:Array of struct of arrays to 2D array数组结构数组到二维数组
【发布时间】:2023-03-18 14:50:02
【问题描述】:

我有以下结构数组:

item.Position=[];
item.Cost=0;
items=repmat(item,1000,1);
for i=1:1000
    items(i).Position = floor(ones(1,5)*rand*10);
    items(i).Cost = rand;
end

我想将位置提取为二维数组。所以,结果应该是:

1 2 3 4 5 6 7
9 2 4 1 0 3 4 
5 4 3 2 4 9 8
....
0 2 4 8 6 3 1 

是否可以在 MATLAB 中不循环?

【问题讨论】:

    标签: matlab struct


    【解决方案1】:

    您可以使用[] 收集items.Position 的输出。但是,这会将其收集为一个长数组。因此,要获得矩阵,您必须对其进行重塑,即类似于

    %Build data
    item.Position=[ 1 2 3 4 5 6 7];
    item.Cost=0;
    items=repmat(item,1000,1);
    
    %Collect output
    tmp = [items.Position];
    
    %Reshape
    res = reshape(tmp,7,[]).';
    

    收集和重塑当然可以一步完成,为了清楚起见,我只是把它分开了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多