我有一个结构数组:1x10结构数组,字段:N,t,q,r,T,每个都是double
类型的向量。
10个数组条目分别代表实验中测试条件的结果。我希望能够创建一个带有两个索引index1
和index2
的函数,并修改组成N,t,q,r向量(T是单个数字),以便它们成为长度index1
:index2
。像
function sa = modifier(struct_array, index1, index2)
sa = structfun(@(x) x(index1:index2), struct_array, 'UniformOutput', false)
stuff
end
现在,在stuff
的位置,我尝试使用structfun
和cellfun
,请参阅here,除了那些分别返回结构和单元格数组,我需要返回一个 struct array 。
这样做的目的是能够得到实验结果的某些部分,例如:也许每个单元格内每个向量中的前五个条目对应于实验的初始循环。
请告诉我这是否可行,以及我如何去做!
答案 0 :(得分:1)
你可以试试这个:
从这个问题的answer,我想出了如何遍历struct字段。我通过从每个遍历for循环的字段中提取子样本,然后将该数据的所需子集复制到具有相同命名字段的新结构数组中来修改代码以解决您的问题。
% Define indexes for extraction
fieldsToTrim = {'a' 'b'};
idx = 2:3; % Create index vector for extracting selected data range
% Define test struct to be read
teststruct.a = [1 2 3];
teststruct.b = [4 5 6];
teststruct.c = [7 8 9];
% Get names of struct fields
fields = fieldnames(teststruct);
% Loop through each field and extract the subset
for i = 1:numel(fields)
if max(strcmp(fields{i},fieldsToTrim)) > 0
% If current matches one of the fields selected for extraction
% extract subset
teststructResults.(fields{i}) = teststruct.(fields{i})(idx);
else
% Else, copy all contents on field to resulting struct
teststructResults.(fields{i}) = teststruct.(fields{i});
end
end
最后,要将其转换为函数,您可以将上述代码修改为:
function teststructResults = extractSubsetFromStruct(teststruct,fieldsToTrim,idx1, idx2)
% idx1 and idx2 are the start and end indicies of the desired range
% fieldsToTrim is a string array of the field names you want
% included in the trimming, all other fields will be fully copied
% teststruct is your input structure which you are extracting the
% subset from
% teststructResults is the output containing identically named
% struct fields to the input, but only containing data from the selected range
idx = idx1:idx2; % Create index vector for extracting selected data range
% Get names of struct fields
fields = fieldnames(teststruct);
% Loop through each field and extract the subset
for i = 1:numel(fields)
if max(strcmp(fields{i},fieldsToTrim)) > 0
% If current matches one of the fields selected for extraction
% extract subset
temp = teststruct.(fields{i});
teststructResults.(fields{i}) = temp(idx);
else
% Else, copy all contents on field to resulting struct
teststructResults.(fields{i}) = teststruct.(fields{i});
end
end
end
我成功运行了这样的功能:
teststruct =
a: [1 2 3]
b: [4 5 6]
c: [7 8 9]
>> extractSubsetFromStruct(teststruct,{'a' 'b'},2,3)
ans =
a: [2 3]
b: [5 6]
c: [7 8 9]