How can I access the nth element of all the arrays in a structure of arrays?

18 次查看(过去 30 天)
I have a structure with M fields, and I wish each field to contain an array of N elements. I wish to access the data for each field in one call (plane organization), but I am loading data to the structure on an element-by-element basis.
example:
S.f1=zeros(1,10)
S.f2=ones(1,10)
X.f1=55
X.f2=56
I want to assign X to the second element of all fields of S so that S.f1 contains 0,55,0,0,0,0,0,0,0,0 S.f2 contains 1,56,1,1,1,1,1,1,1,1

采纳的回答

Guillaume
Guillaume 2015-4-17
编辑:Guillaume 2015-4-17
One possible way:
S.f1 = zeros(1,10)
S.f2 = ones(1,10)
X.f1 = 55;
X.f2 = 56;
repindex = 2
for field = fieldnames(X)'
%field is a 1x1 cell array that iterates over the fields of X
S.(field{1})(repindex) = X.(field{1});
end
Edit: Actually, it may just be simpler to convert your structure into a matrix, fill it up, and convert it back to a structure. This assumes that all fields are row vectors of the same size, though:
%convert S to matrix:
Smat = cell2mat(struct2cell(S));
%load the data element-by-element:
Smat(:, repindex) = cell2mat(struct2cell(X));
%when all done convert back to struct:
S = cell2struct(num2cell(Smat, 2), fieldnames(S))
I'll leave both solution up for you to choose.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by