Indexing through a structure to get subsets of data with no looping
1 次查看(过去 30 天)
显示 更早的评论
dataArray = [21,22,23,24,25,26,27,28,29,30];
structureOfIndexes.a1 = [2,8];
structureOfIndexes.a2 = [1,5,7];
%if I want to grab the next 3 values in dataArray starting from each index such that:
%resultStructure.a1 = [22 23 24 28 29 30]
%resultStructure.a2 = [21 22 23 25 26 27 27 28 29]
% Trying the code below yields:
resultStructure = structfun(@(x) dataArray(x:x+2), structureOfIndexes, "UniformOutput", false)
0 个评论
采纳的回答
Eric Delgado
2022-9-27
Look... why you don't want to use a loop?! It's something that you can't avoid sometimes. The result you are looking for is weird, maybe you can work with tables and dict (new Matlab data type) instead of struct.
In "my solution" you have two loops! :)
% input
dataArray = [21,22,23,24,25,26,27,28,29,30];
structureOfIndexes.a1 = [2,8];
structureOfIndexes.a2 = [1,5,7];
% Loops... thanks God!
fn = fieldnames(structureOfIndexes);
for ii = 1:numel(fn)
tempValues = [];
for jj = 1:numel(structureOfIndexes.(fn{ii}))
idx = structureOfIndexes.(fn{ii})(jj);
tempValues = [tempValues, dataArray(idx:idx+2)];
end
resultStructure.(fn{ii}) = tempValues;
end
resultStructure
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Migrate GUIDE Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!