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

29 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 17 Apr 2015
Edited: Guillaume on 17 Apr 2015
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.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!