How can I access the nth element of all the arrays in a structure of arrays?
조회 수: 36 (최근 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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!