Using the fields of a structure to index through a vector and generate a resulting structure

2 ビュー (過去 30 日間)
dataArray = [21,22,23,24,25,26,27,28,29,30];
structureOfIndexes.a1 = [2,5,8];
structureOfIndexes.a2 = [3,4];
structureOfIndexes.a3 = [1,2,3,5,9];
% How do I use the structure of indexes to generate the 'resultStructure'(seen below)
resultStructure.a1 = [22,25,28];
resultStructure.a2 = [23,24];
resultStructure.a3 = [21,22,23,25,29];
% without using a for-loop to index through a1,a2,a3

採用された回答

Eric Delgado
Eric Delgado 2022 年 9 月 27 日
Hey @Scorp, structfun is the answer for your issue! :)
dataArray = [21,22,23,24,25,26,27,28,29,30];
structureOfIndexes.a1 = [2,5,8];
structureOfIndexes.a2 = [3,4];
structureOfIndexes.a3 = [1,2,3,5,9];
resultStructure = structfun(@(x) dataArray(x), structureOfIndexes, "UniformOutput", false)
resultStructure = struct with fields:
a1: [22 25 28] a2: [23 24] a3: [21 22 23 25 29]
  1 件のコメント
Scorp
Scorp 2022 年 9 月 27 日
%Thank you for your reply, a further question:
%if I want to grab the next 3 values in dataArray from each index such that:
dataArray = [21,22,23,24,25,26,27,28,29,30];
structureOfIndexes.a1 = [2,8];
% Trying the code below yields a1: [22 23 24]
resultStructure = structfun(@(x) dataArray(x:x+2), structureOfIndexes, "UniformOutput", false)
resultStructure = struct with fields:
a1: [22 23 24]
% but I want the output to be: resultStructure.a1 = [22,23,24,28,29,30];

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by