How to access all elements within a structured cell array without looping?

I have a variable that look like this:
a_structure{1}.field1=vector1;
a_structure{2}.field1=vector2;
a_structure{3}.field1=vector3;
Without looping, how do I obtain the matrix that puts vector1 in column 1, vector2 in column 2 and vector3 in column 3?
Note: The {} in there is intentional. I am not using the structure(1).field1 syntax. I could get there, but would have thousands of lines of code to change.

 採用された回答

Cam Salzberger
Cam Salzberger 2020 年 3 月 4 日
Hello Steve,
I would suggest restructuring your data storage. If you did use the struct array method of storage, I believe it would be as simple as [a_structure.field1]. But taking it as it is, you can fairly easily transform the cell array of similar structures into a struct array with this:
sArr = [a_structure{:}];
And then extract the fields into a matrix with my original method:
A = [sArr.field1];
The structures would need to be similar though. If the first line fails because they are not, you may need to use cellfun:
C = cellfun(@(c) c.field1, a_structure, 'UniformOutput', false);
A = [C{:}];

1 件のコメント

SteveR
SteveR 2020 年 3 月 4 日
WE HAVE A WINNER!!!! Thanks a ton, Cam! I knew there was something better than a loop out there (I was going down the subsref rabbit hole when I decided to post my first question here instead).
Rest assured, I will update my code to () syntax when I have enough spare time to ensure equivalent performance across the multitude of twists and turns my code takes. :)

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

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 3 月 4 日
編集済み: Stephen23 2020 年 3 月 4 日
"I am not using the structure(1).field1 syntax"
You should be. It would allow you to use efficient syntaxes for accessing your data (i.e. like you are asking about now):
If all of the structures in the cell array have the same fields and have compatible sizes, then you can concatenate them together, e.g. where C is your cell array:
S = [C{:}]; % concatenate unfortunate cell of structs into better non-scalar structure.
M = [S.field1] % concatenate field1 vectors [S(1).field1,S(2).field1,S(3).field1,...]
Read more:

1 件のコメント

SteveR
SteveR 2020 年 3 月 4 日
I realized my error regarding the superiority of the () syntax some time ago, but project deadlines have kept me from fixing the thousands of lines of code I have across several different analysis tools.

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

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

リリース

R2019b

質問済み:

2020 年 3 月 4 日

コメント済み:

2020 年 3 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by