I have an array of structures. Each structure is composed of a matrix. I need to extract a particular element of the matrix for every structure element. For example: i/p: if s is an array of 2 structures such that, s(1) = struct('field1', [1:3;4:6]); s(2) = struct('field1', [4:6;1:3]); o/p: [s(1).field1(1,3) s(2).field1(1,3)]; I can do it by the use of loops, but is there any efficient way to do it??

 採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 6 月 28 日

0 投票

s(1) = struct('field1', [1:3;4:6]);
s(2) = struct('field1', [4:6;1:3]);
z = cell2mat(struct2cell(s))
out = squeeze(z(1,3,:))'

5 件のコメント

Sugyani Mahapatra
Sugyani Mahapatra 2017 年 6 月 28 日
What if my structure contains more than 1 fields and the fields are matrices of different dimension??
Andrei Bobrov
Andrei Bobrov 2017 年 6 月 28 日
please example..
Sugyani Mahapatra
Sugyani Mahapatra 2017 年 6 月 28 日
s(1) = struct('field1', [1:3;4:6], 'field2', [1:10]); s(2) = struct('field1', [4:6;1:3], 'field2', [11:20]);
o/p: [s(1).field1(1,3) s(2).field1(1,3)];
I tried your above suggested method but that gives the following error: "Error using cell2mat (line 45) All contents of the input cell array must be of the same data type."
Andrei Bobrov
Andrei Bobrov 2017 年 6 月 28 日
s(1) = struct('field1', [1:3;4:6], 'field2', [1:10]);
s(2) = struct('field1', [4:6;1:3], 'field2', [11:20]);
t = cat(3,s.field1);
out = squeeze(t(1,3,:))'
Sugyani Mahapatra
Sugyani Mahapatra 2017 年 6 月 28 日
Cool...!!!
Thank you so much, sir. That works..!!!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by