re-order array structs of arrays
이전 댓글 표시
I have a struct array, x, with two fields, x.fld1 and x.fld2. x has n indices and all fields have m indices like x(1:n).fld1(1:m) and x(1:n).fld2(1:m). I want to re-order the struct to y(1:m).fld1(1:n) and y(1:m).fld2(1:n). Any ideas besides a triple for-loop cycling over the x indices, the fields, and the fld indices? Also, how would you pre-allocate y?
% my long way flds = fieldnames(x); nflds = length( flds ); n = length(x); m = length(x(1).fld{1}); for i = 1:n for j = 1:m for k = 1:nflds y(i).(flds{k})(j) = x(j).(flds{k})(i); end end end
채택된 답변
추가 답변 (1개)
Guillaume
2018년 10월 16일
Convert to cell array with struct2cell, then to matrix, rearrange the dimension, and convert back to cell array then structure:
If the fields and the structure are row vectors:
tempmat = cell2mat(struct2cell(x)); %note that the cell2mat call will fail if not all fields are the same size
tempmat = permute(tempmat, [1 3 2]);
newx = cell2struct(num2cell(tempmat, 2), fieldnames(x), 1)
If the field or the structure or both are not row vectors, then specify what they are as writing a generic version that can cope with vectors in any dimension would be a pain.
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!