Efficient way to change a struct of (mixed-type) arrays into a structure array?

3 ビュー (過去 30 日間)
David Goldsmith
David Goldsmith 2012 年 8 月 17 日
Hi! Resulting from a DB query, I have a 6-field scalar struct consisting of 1522-element arrays, some cell, some numeric (if that matters); I want to convert it into a 1522x1 struct array with the same six fields--is there a non-for-loop way to do this?
  1 件のコメント
Jan
Jan 2012 年 8 月 18 日
Please provide example data in valid Matlab syntax. "6-field scalar struct consisting of 1522-element arrays, some cell, some numeric" does neither define the inputs nor the wanted output unequivocally. As you see in the given answers, forcing contributors to guess the details is no efficient method to get your problem solved.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2012 年 8 月 17 日
編集済み: Walter Roberson 2012 年 8 月 17 日
I am not sure if there is a loop-less way to handle the situation if the field names are not known in advance. But perhaps the below is good enough, when "A" is your scalar struct:
B = [fieldnames(A).';cellfun(@num2cell,struct2cell(A).','un',0)]
C = struct(B{:}};
  2 件のコメント
David Goldsmith
David Goldsmith 2012 年 8 月 17 日
Same comment as below.
Walter Roberson
Walter Roberson 2012 年 8 月 18 日
In my tests, the code works with cells as well. I have not tried with nested structures or objects, though.
Looking at the code for num2cell(), I can see that the code should work for any field which can be handle numel() and linear subscript referencing.

サインインしてコメントする。


Azzi Abdelmalek
Azzi Abdelmalek 2012 年 8 月 17 日
編集済み: Azzi Abdelmalek 2012 年 8 月 17 日
% A contains multiple array (num, str,...)
eval(sprintf('a.field%d=A(:,%d);',[1 :6;1:6]))
  5 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 8 月 17 日
tell us what is the size of your cell array: size(A)
Jan
Jan 2012 年 8 月 18 日
No, Azzi, do not use EVAL to access structs. "Dynamic fieldnames" are much more efficient and cleaner: a.(sprintf('field%d', i)). The topic EVAL has been discussed hundreds of times in this forum.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by