Reshaping nested struct arrays to cell array having elements with different sizes

一曲冷凌霜 提交于 2020-01-04 02:19:05

问题


I have a similar question to my previous one. This time the form of the nested structure looks like this:

Sizes = [2, 5, 8, 6, 3];
cells = 5;
for i = 1:cells
    for j = 1:Sizes(i)
        a(i).b.c(j).d = rand(1,1);
    end
    a(i).b.Size = Sizes(i);
end

Again I would like to put all the d values of a(:).b.c(:) into a single cell array that contains 1 x cells cells.

Here is my solution using cellfun but I would like to avoid this function:

ab = [a.b];
abc = {ab.c};
abcd = cellfun(@(x) [x.d], abc, 'UniformOutput', false);

Using the previous solution for abc:

abc = [ab.c];

creates a 1x24 struct array with field d. I thought of using the Size field to reshape this result into a cell array but I don't know how or if it is possible. Do you have a better appraoch without using loops and without cellfun?


回答1:


You can do this using mat2cell as follows:

ab = [a.b];
abc = [ab.c];
abcd = mat2cell([abc.d], 1, [ab.Size]);


来源:https://stackoverflow.com/questions/45571366/reshaping-nested-struct-arrays-to-cell-array-having-elements-with-different-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!