フィルターのクリア

Array of Structures to Structure of arrays

82 ビュー (過去 30 日間)
Andrew C
Andrew C 2021 年 9 月 30 日
回答済み: Chunru 2021 年 10 月 1 日
How can I convert an array of structures into a structure of arrays.
I currently have an array of structs of size N that the only way to access it is to call them by
var = struct(1).fieldname
Where the fieldname is referencing a array of 1xM.
When I try to call var = struct.fieldname or var = struct(:).fieldname I only get one value, while I would like to get all values.
I have tried to do struct2cell and cell2mat, but these options expand the nested array.
What I want is to call each fieldname and get a matrix of NxM.
  2 件のコメント
Jan
Jan 2021 年 9 月 30 日
編集済み: Jan 2021 年 9 月 30 日
The question is not clear yet, because the readers cannot know, how your struct looks like.
Andrew C
Andrew C 2021 年 9 月 30 日
Apologies. I will try to make it a bit clearer

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

回答 (2 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 10 月 1 日
Jan is right that your questions are not quite clear for the reader as described here. But what I've understood is the following:
% Let's say that X is the structure array:
FNames = fieldnames(X); % ALL Field Names residing in X structure array can be obtained
% This part seems to be optional for your exercise:
XX=zeros(length(FNames), 1);
for ii = 1:length(FNames)
xi = getfield(X, FNames{ii}); % Field Values
XX(ii) = xi;
end

Chunru
Chunru 2021 年 10 月 1 日
% array of structure
M = 5;
for i=1:M
a(i).f1 = rand(1,1);
a(i).f2 = rand(1,1);
end
a
a = 1×5 struct array with fields:
f1 f2
a(1)
ans = struct with fields:
f1: 0.6493 f2: 0.9459
% struncrure of array [assuming each field is a scalar in a]
f = fields(a(1));
for i=1:length(f)
b.(f{i}) = [a.(f{i})];
end
b
b = struct with fields:
f1: [0.6493 0.7285 0.1068 0.3718 0.3805] f2: [0.9459 0.5456 0.5360 0.2124 0.6030]

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by