从结构的多个字段中提取行

Extract rows from multiple fields of a structure

创建了列向量(100 行)的结构(25 个字段)。如何提取其特定行。例如,

s.a=[1 2 3 4 5 6]'
s.b=[5 2 8 1 0 4]'
s.c=[9 7 0 1 3 5]'
% 2 to 4 rows to be extracted
% expected output
t.a=[2 3 4]'
t.b=[2 8 1]'
t.c=[7 0 1]'

结构索引无效。 通用方法是什么。

使用函数 struct2array 将结构转换为数组,提取行,然后再转换回来。

s.a=[1 2 3 4 5 6]';
s.b=[5 2 8 1 0 4]';
s.c=[9 7 0 1 3 5]';
lowest_row=2;
highest_row=4;
num_of_fields=length(fieldnames(s)); % Will be 25 in your code

mat = struct2array(s); % Convert struct to matrix
extracted_mat = mat(lowest_row:highest_row,:); % Extract wanted rows from mat

abc_vec=char(97:122);

% Convert back to struct
for i=1:num_of_fields
    t.(abc_vec(i))=extracted_mat(:,i);
end

只是 select 结构中的特定行。

% getting the fieldnames of the struct
field = fieldnames(s)

% length of the struct

len = length(field)

startRow = 2;
endRow = 4;

for ii = 1:1:len
   t.(field{ii,1}) = s.(field{ii,1})(startRow:endRow)
end

您可以简单地使用 structfun

t = structfun(@(x)x(2:4),s,'UniformOutput',false)