Indexing through a structure to get subsets of data with no looping

조회 수: 1 (최근 30일)
Scorp
Scorp 2022년 9월 27일
댓글: Scorp 2022년 9월 27일
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)
resultStructure = struct with fields:
a1: [22 23 24] a2: [21 22 23]

채택된 답변

Eric Delgado
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
resultStructure = struct with fields:
a1: [22 23 24 28 29 30] a2: [21 22 23 25 26 27 27 28 29]
  댓글 수: 1
Scorp
Scorp 2022년 9월 27일
My data sets are very large. The dataArray is in the order of 20GB and I need to pull out 20 or so subsets of about 200MB each all with different indexing. I will look at the dictionary option or I will just have to accept the time hit. Thank you for your help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by